uwp之图片旋转动画实现
程序员文章站
2022-07-13 11:43:00
...
先放效果图。类似网易云音乐播放音乐时封面旋转效果
两种实现方式,分别是前端(xaml)和后台(c#代码)实现,右边的图片旋转是在xaml实现,左边的长方形(其实是个Button控件)旋转是在c#代码里面实现
xaml代码如下
<Grid x:Name="LayoutRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
</Grid.Resources>
<!--Ellipse是绘制一个椭圆形-->
<Ellipse x:Name="ellipse" Width="200" Height="200" RenderTransformOrigin="0.5,0.5">
<Ellipse.RenderTransform>
<CompositeTransform/>
</Ellipse.RenderTransform>
<Ellipse.Resources>
<!--Storyboard是一个动画容器-->
<Storyboard x:Name="EllStoryboard" RepeatBehavior="Forever">
<DoubleAnimation Duration="0:0:20" To="360" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.Rotation)" Storyboard.TargetName="ellipse" d:IsOptimized="True"/>
</Storyboard>
</Ellipse.Resources>
<!--这是用一张图片来填充这个椭圆形-->
<Ellipse.Fill>
<ImageBrush x:Name="picture" ImageSource="Assets\30.jpg" />
</Ellipse.Fill>
</Ellipse>
<Button x:Name="button" Width="50" Height="30" Margin="10">
</Button>
</Grid>
//图片旋转动画开始
EllStoryboard.Begin();
//图片旋转动画暂停
EllStoryboard.Pause();
//图片旋转动画结束
EllStoryboard.Stop();
在.cs文件里面用c#代码来实现Button的旋转
private void Rotation()
{
button.RenderTransformOrigin = new Point(0.5, 0.5);
CompositeTransform c = new CompositeTransform();
button.RenderTransform = c;
Storyboard storyboard = new Storyboard();
DoubleAnimation animation = new DoubleAnimation
{
From = 0,
To = 360,
Duration = new Duration(TimeSpan.FromSeconds(20)),
};
Storyboard.SetTarget(animation, button);
Storyboard.SetTargetName(animation, "button");
Storyboard.SetTargetProperty(animation, "(UIElement.RenderTransform).(CompositeTransform.Rotation)");
storyboard.Children.Add(animation);
}
其实C#代码就是用代码把xaml里的属性加进去而已
最后附上微软官方文档对RenderTransform、CompositeTransform、Ellipse、Storyboard的说明
RenderTransform :https://msdn.microsoft.com/zh-cn/library/system.windows.uielement.rendertransform(v=vs.110).aspx
CompositeTransform :https://msdn.microsoft.com/zh-cn/library/system.windows.media.compositetransform(v=vs.95).aspx
Ellipse :https://msdn.microsoft.com/zh-cn/library/system.windows.shapes.ellipse(v=vs.110).aspx
Storyboard: https://msdn.microsoft.com/zh-cn/library/system.windows.media.animation.storyboard(v=vs.110).aspx