首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發 WPF/Silverlight 動畫與遊戲系列教程(三)讓物體動起來 ③(一)—— DispatcherTimer 定時器動畫實作

     編輯:關於C語言

DispatcherTimer 動畫特點

與 CompositionTarget 同屬幀動畫,但可輕鬆配置參數。

完整實作代碼

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();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved