第三種方法,DispatcherTimer動畫,該類型動畫與CompositionTarget動畫類似,是基於界面線程的逐幀動畫,但他與CompositionTarget動畫不同,DispatcherTimer動畫可以輕松的進行參數設置:
xaml界面代碼仍然沿用第一節的,那麼接下來我們在後台代碼中創建相關對象:
Rectangle rect; //創建一個方塊作為演示對象
double speed = 5; //設置移動速度
Point moveTo; //設置移動目標
public Window3() {
InitializeComponent();
rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = 50;
rect.Height = 50;
rect.RadiusX = 5;
rect.RadiusY = 5;
CarrIEr.Children.Add(rect);
Canvas.SetLeft(rect, 0);
Canvas.SetTop(rect, 0);
//定義線程
DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
dispatcherTimer.Tick += new EventHandler(Timer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50); //重復間隔
dispatcherTimer.Start();
}
private void CarrIEr_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
moveTo = e.GetPosition(CarrIEr);
}
private void Timer_Tick(object sender, EventArgs e) {
double rect_X = Canvas.GetLeft(rect);
double rect_Y = Canvas.GetTop(rect);
Canvas.SetLeft(rect, rect_X + (rect_X < moveTo.X ? speed : -speed));
Canvas.SetTop(rect, rect_Y + (rect_Y < moveTo.Y ? speed : -speed));
}
與上一節的代碼類似,不同的地方其實也就是聲明動畫線程處,共4句:
DispatcherTimer dispatcherTimer = new DispatcherTimer(DispatcherPriority.Normal);
dispatcherTimer.Tick += new EventHandler(Timer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);
dispatcherTimer.Start();