WPF中的DoubleAnimation
周銀輝
DoubleAnimation指定一個Double類型的屬性,使其在指定的時間內由起點值到達終點值,從而形成動畫效果.
應用它來實現動畫效果,只要簡單地指定幾個參數值就可以了.
看下面的代碼是改變一個按鈕的大小的動畫 //指定長度變化的起點,終點與期間
DoubleAnimation widthAnimation =
new DoubleAnimation(200, 400, new Duration(TimeSpan.FromSeconds(0.8)));
//指定高度變化的起點,終點與期間
DoubleAnimation heightAnimation =
new DoubleAnimation(50, 100, new Duration(TimeSpan.FromSeconds(0.8)));
//開始動畫
//變化不是阻塞的,而是非同步,所以看上去長度與高度幾乎是同時變化
btn.BeginAnimation(Button.WidthProperty, widthAnimation);
btn.BeginAnimation(Button.HeightProperty, heightAnimation);
這樣我們就可以得到一個簡單的動畫,它在0.8秒內將按鈕的長度由200變化到400,高度由50變化到100.
但我們會發現當動畫結束後,按鈕的大小保持在(400,100), 如果我們需要動畫結束後將按鈕大小恢複到原大小,那麼我們應該指定另外一個參數:
FillBehavior//指定長度變化的起點,終點與期間,並在動畫結束時恢複原值
DoubleAnimation widthAnimation =
new DoubleAnimation(200, 400, new Duration(TimeSpan.FromSeconds(0.8)), FillBehavior.Stop);
//指定高度變化的起點,終點與期間,並在動畫結束時恢複原值
DoubleAnimation heightAnimation =
new DoubleAnimation(50, 100, new Duration(TimeSpan.FromSeconds(0.8)), FillBehavior.Stop);
以下是完整的執行個體代碼:using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
namespace DoubleAnimationTest
{
/**//// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : System.Windows.Window
{
private Grid gridRoot;
private Button buttonTest;
public Window1()
{
IniComponent();
}
private void IniComponent()
{
this.gridRoot = new Grid();
this.buttonTest = new Button();
this.buttonTest.Content = "this is a test button";
this.buttonTest.Width = 200;
this.buttonTest.Height = 50;
this.buttonTest.Click += new RoutedEventHandler(buttonTest_Click);
this.gridRoot.Children.Add(this.buttonTest);
this.Content = gridRoot;
}
void buttonTest_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
//指定長度變化的起點,終點與期間,並在動畫結束時保持大小
DoubleAnimation widthAnimation =
new DoubleAnimation(200, 400, new Duration(TimeSpan.FromSeconds(0.8)), FillBehavior.HoldEnd);
//指定高度變化的起點,終點與期間,並在動畫結束時保持大小
DoubleAnimation heightAnimation =
new DoubleAnimation(50, 100, new Duration(TimeSpan.FromSeconds(0.8)), FillBehavior.HoldEnd);
//開始動畫
//變化不是阻塞的,而是非同步,所以看上去長度與高度幾乎是同時變化
btn.BeginAnimation(Button.WidthProperty, widthAnimation);
btn.BeginAnimation(Button.HeightProperty, heightAnimation);
}
}
public class MainClass
{
[STAThread]
public static void Main()
{
Window1 win = new Window1();
Application app = new Application();
app.Run(win);
}
}
}