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

C# 開發 WPF/Silverlight 動畫與遊戲系列教程(一)讓物體動起來 ①(二)—— Storyboard 動畫實作

     編輯:關於C語言

介面容器佈局

建立名為 Carrier 的 Canvas(800×600,銀色背景),註冊滑鼠左鍵點擊事件。選擇 Canvas 因其支援子元素絕對定位,便於處理物體移動。

動態建立物體

Rectangle rect;
public Window1() {
    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);
}

建立 50×50 圓角紅色方塊,加入 Carrier,初始位置 (0,0)。

滑鼠點擊觸發移動動畫

private void Carrier_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    Point p = e.GetPosition(Carrier);
    Storyboard storyboard = new Storyboard();

    // X 軸動畫
    DoubleAnimation doubleAnimation = new DoubleAnimation(
        Canvas.GetLeft(rect), p.X, new Duration(TimeSpan.FromMilliseconds(500)));
    Storyboard.SetTarget(doubleAnimation, rect);
    Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
    storyboard.Children.Add(doubleAnimation);

    // Y 軸動畫
    doubleAnimation = new DoubleAnimation(
        Canvas.GetTop(rect), p.Y, new Duration(TimeSpan.FromMilliseconds(500)));
    Storyboard.SetTarget(doubleAnimation, rect);
    Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
    storyboard.Children.Add(doubleAnimation);

    // 動態加入資源並播放
    if (!Resources.Contains("rectAnimation"))
        Resources.Add("rectAnimation", storyboard);
    storyboard.Begin();
}

點擊處即為目標座標,分別建立 X、Y 方向的 DoubleAnimation,目標屬性為 Canvas.Left/Top,時長 500ms,加入 Storyboard 播放。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved