如何使用c#或XAML创建自动动画旋转图像
本文关键字:动画 旋转 图像 创建 何使用 XAML | 更新日期: 2023-09-27 18:06:37
我在web开发中做过轮播,但通过XAML或c#在WPF中动画它们对我来说是新的。网上有一些例子,但它们要么过时了,要么不是我想要的。甚至当我摆弄其他项目的源代码时,它也不是我所希望的。
我想让图像自动从左向右滑动(水平)。用户不能与图像交互来阻止滑动。虽然我可以在ScrollViewer
中手动执行此操作,但该过程是手动的…
ScrollViewer
没有任何动画依赖。我试着用这个来看看是否可能,但是应用程序总是崩溃。我用了…
我尝试过的另一个尝试是将图像存储在StackPanel
中,确保StackPanel
是我的图像之一的宽度,然后将DispatcherTimer
设置为动画TranslateTransform
的X属性。但是…
使用ScrollViewer
或StackPanel
根本不重要。我只是想有一个旋转木马式的效果,自动通过图像过渡。有点像THIS
我目前正在使用Visual Studio 2012和2013,如果它有帮助。有办法做到这一点吗?
我在wpf中准备了示例性的旋转木马。例如,您可能希望以UserControl的形式使用代码。正如你所建议的,我准备了使用StackPanel的旋转木马。我的表单代码如下所示:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Storyboard x:Key="CarouselStoryboard">
<DoubleAnimation
Storyboard.TargetName="CarouselTransform"
Storyboard.TargetProperty="X"/>
</Storyboard>
</Window.Resources>
<Canvas>
<StackPanel Name="Carousel" Orientation="Horizontal">
<StackPanel.RenderTransform>
<TranslateTransform x:Name="CarouselTransform" />
</StackPanel.RenderTransform>
<Button Height="350" Width="525" Content="Page1"/>
<Button Height="350" Width="525" Content="Page2"/>
<Button Height="350" Width="525" Content="Page3"/>
</StackPanel>
<Button Click="Left_Click" Content="Left" HorizontalAlignment="Left" Margin="10,164,0,0" VerticalAlignment="Top" Width="45">
</Button>
<Button Click="Right_Click" Content="Right" HorizontalAlignment="Left" Margin="448,170,0,0" VerticalAlignment="Top" Width="45"/>
</Canvas>
</Window>
WindowResources中的Storyboard元素定义了要执行的动画。它将改变应用于StackPanel"Carousel"的TranslationTransform的X属性-这将导致该面板的动画运动。面板内的3个按钮模拟了旋转木马的3个面板。底部有两个按钮-一个用于向左移动,第二个用于向右移动。有绑定到它们的回调方法。表单后面的代码如下所示:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int currentElement = 0;
private void Left_Click(object sender, RoutedEventArgs e)
{
if(currentElement < 2)
{
currentElement++;
AnimateCarousel();
}
}
private void Right_Click(object sender, RoutedEventArgs e)
{
if (currentElement > 0)
{
currentElement--;
AnimateCarousel();
}
}
private void AnimateCarousel()
{
Storyboard storyboard = (this.Resources["CarouselStoryboard"] as Storyboard);
DoubleAnimation animation = storyboard.Children.First() as DoubleAnimation;
animation.To = -this.Width * currentElement;
storyboard.Begin();
}
}
currentElement字段保存当前显示给用户的面板的信息。方法AnimateCarousel实际开始动画。它引用了参考资料中定义的故事板,并将其DoubleAnimation to属性设置为Carousel面板应该移动到的值。然后通过在storyboard上调用Begin方法来执行动画