這段代碼我創建了一個名叫CarrIEr的Canvas(畫布)容器布局控件,並設置它的尺寸為800*600,背景銀色,最後注冊一個鼠標在它上面點擊的事件。那麼為什麼要選擇Canvas作為容器呢?因為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象素,圓角5*5紅色的方塊對象,並且將它作為子控件添加進Carrier中,並且初始化它在CarrIEr中的位置: Canvas.SetLeft(rect, 0); Canvas.SetTop(rect, 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();
}