如何在 wpf 中实现背景图像连续移动
本文关键字:背景 图像 连续 移动 实现 wpf | 更新日期: 2023-09-27 18:34:41
我的wpf应用程序中有一个背景图像,我想实现背景图像连续移动的效果。下面的代码可以实现一个简单的效果,但是当图片结束的时间再次移动时,我想让这张图片的效果
一直移动的现象没有停止。void StartBackgroudMove()
{
Storyboard sb = new Storyboard();
DoubleAnimation TranslateXExtendAnimation = new DoubleAnimation() { From = 0, To = -100, Duration = TimeSpan.FromMilliseconds(2500) };
Storyboard.SetTarget(TranslateXExtendAnimation, BackgroundImage);
Storyboard.SetTargetProperty(TranslateXExtendAnimation, new PropertyPath("(FrameworkElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"));
sb.Children.Add(TranslateXExtendAnimation);
sb.FillBehavior = FillBehavior.Stop;
sb.Completed += (s, args) =>
{
this.StartBackgroudMove();
};
sb.Begin();
}
您可以使用设置为TileMode
的 ImageBrush 来Tile
其Viewport
属性并设置动画:
<Grid>
<Grid.Background>
<ImageBrush ImageSource="C:'Users'Public'Pictures'Sample Pictures'Desert.jpg"
Stretch="Fill" TileMode="Tile"
ViewportUnits="Absolute" Viewport="0,0,1024,768"/>
</Grid.Background>
<Grid.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<RectAnimation Storyboard.TargetProperty="Background.Viewport"
To="-1024,0,1024,768" Duration="0:0:10"
RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
</Grid>
以下替代解决方案将两个相邻的图像放置在画布中,并对画布的 RenderTransform
属性进行动画处理。
<Grid>
<Canvas>
<Canvas.RenderTransform>
<TranslateTransform x:Name="translation"/>
</Canvas.RenderTransform>
<Image Stretch="None"
Source="C:'Users'Public'Pictures'Sample Pictures'Desert.jpg"/>
<Image Canvas.Left="1024" Stretch="None"
Source="C:'Users'Public'Pictures'Sample Pictures'Desert.jpg"/>
</Canvas>
<Grid.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="X"
Storyboard.TargetName="translation"
To="-1024" Duration="0:0:10"
RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
</Grid>
您可以将
Storyboard.RepeatBehavior
设置为RepeatBehavior.Forever
例:
void StartBackgroudMove()
{
Storyboard sb = new Storyboard();
DoubleAnimation TranslateXExtendAnimation = new DoubleAnimation() { From = 0, To = -100, Duration = TimeSpan.FromMilliseconds(2500) };
Storyboard.SetTarget(TranslateXExtendAnimation, BackgroundImage);
Storyboard.SetTargetProperty(TranslateXExtendAnimation, new PropertyPath("(FrameworkElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"));
sb.Children.Add(TranslateXExtendAnimation);
sb.FillBehavior = FillBehavior.Stop;
sb.RepeatBehavior = RepeatBehavior.Forever;
sb.Begin();
}