一,使用DoubleAnimation创建动画
//1,创建剧本 Storyboard storyboard = new Storyboard(); //2,创建动画 DoubleAnimation doubleAnimation = new DoubleAnimation( valueStart,//起始值 valueEnd,//终点值 new Duration(TimeSpan.FromMilliseconds(1000s))//动画时间域 ); //3,Target Storyboard.SetTarget(doubleAnimation, rect);//Target对象 Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));//Target属性 //4,在剧本中添加动画 storyboard.Children.Add(doubleAnimation); //5,在资源中添加剧本 if(!Resources.Contains("animation")) { Resources.Add("animation", storyboard); } //6,开始 storyboard.Begin();
二,使用CompositionTarget
CompositionTarget对象可以根据每个帧回调来创建自定义动画。
1,注册事件
CompositionTarget.Rendering += new EventHandler(ReflashView);
2,事件的实现
private void ReflashView(object sender, EventArgs e) { double rectX = Canvas.GetLeft(rect); double rectY = Canvas.GetTop(rect); //算法自拟 Canvas.SetLeft(rect, valueX); Canvas.SetTop(rect, valueY); }
三, DispatcherTimer动画
基于界面线程的逐帧动画,与CompositionTarget动画不同,DispatcherTimer动画可以很轻松的通过Interval 来控制刷新一个对象属性的频率了。
1, 创建一个DispatchTimer
DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal); dispatcherTimer.Tick += dispatcherTimer_Tick; dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50); dispatcherTimer.Start();
2, 实现dispatcherTimer_Tick函数
void dispatcherTimer_Tick(object sender, EventArgs e)
{
double rectX = Canvas.GetLeft(rect); double rectY = Canvas.GetTop(rect); //算法自拟 Canvas.SetLeft(rect, valueX); Canvas.SetTop(rect, valueY);
}