2008年3月18日星期二

Silverlight - Animations Programmatically With C#/VB

既然SL 2.0支援.NET Language,除了用StoryBoard之外,當然還可以如WPF / Xbap般,使用程式去做動畫喇。
以下是其中一個例子,由10x10的正方形漸變大小至600x400:
public void Create_And_Run_Animation()
{
//新建一個10x10和紅色的正方形
Rectangle myRectangle = new Rectangle();
myRectangle.Width = 10;
myRectangle.Height = 10;
Color myColor = Color.FromArgb(255, 255, 0, 0);
SolidColorBrush myBrush = new SolidColorBrush();
myBrush.Color = myColor;
myRectangle.Fill = myBrush;

//把正方形加進既LayoutRoot的子集
LayoutRoot.Children.Add(myRectangle);

//Duration設成8秒,時間越短越快,你可以想像成Timeline一樣
Duration duration = new Duration(TimeSpan.FromSeconds(0.8));

//因為我們需要同時改變寬和高,所以要建立兩個DoubleAnimation
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();

myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;

//新增StoryBoard
Storyboard sb = new Storyboard();
sb.Duration = duration;

sb.Children.Add(myDoubleAnimation1);
sb.Children.Add(myDoubleAnimation2);

//把目標轉向myRectangle和Property
Storyboard.SetTarget(myDoubleAnimation1, myRectangle);
Storyboard.SetTarget(myDoubleAnimation2, myRectangle);
Storyboard.SetTargetProperty(myDoubleAnimation1, "(Rectangle.Width)");
Storyboard.SetTargetProperty(myDoubleAnimation2, "(Rectangle.Height)");

myDoubleAnimation1.To = 600;
myDoubleAnimation2.To = 400;

//放進Resouce,就好似使用Blend建立的StoryBoard 時一樣
LayoutRoot.Resources.Add(sb);

//開始動畫
sb.Begin();
}

沒有留言:

發佈留言