WPF -- 構建動畫

寫在前面:本文代碼摘自《Head First C#》app

本文使用ObjectAnimationUsingKeyFrames + Storyboard構建一個動畫。函數

ObjectAnimationUsingKeyFrames爲關鍵幀動畫,它容許爲動畫設置幾個關鍵幀,其中每一幀爲ObjectKeyFrame類型。ObjectKeyFrame爲抽象類,實際使用的是DiscreteObjectKeyFrame,它是ObjectKeyFrame的派生類,表示目標是不連續變化的。ObjectAnimationUsingKeyFrames的KeyFrames屬性即爲關鍵幀集合。DiscreteObjectKeyFrame的Value屬性爲該幀的值,KeyTime屬性爲該幀的時間點信息。動畫

Storyboard可執行一組動畫,下面的示例代碼只包含一個動畫。其SetTarget方法指定執行動畫的界面元素,SetTargetProperty方法指定該動畫應用到該界面元素的哪一個屬性上。定義並設置好動畫後,將動畫添加到Storyboard的Children中。this

RepeatBehavior屬性表示動畫的重複行爲。取值爲0表明不播放,取其它double值控制循環次數,取RepeatBehavior.Forever表示一直循環。AutoReverse屬性表示是否以相反的動畫方式從終止值返回起始值。code

// 前臺,UserControl標記的代碼
<Grid>
    <Image x:Name="iamge" Streach="Fill" />
</Grid>

// 後臺代碼
public sealed partial class AnimatedImage:UserControl
{
    // 使用xaml建立控件,必須有一個無參構造函數
    public AnimatedImage()
    {
        this.InitializeComponent();
    }

    publi AnimatedImage(IEnumerable<string> imageNames, TimeSpan interval)
        :this()
    {
        StartAnimation(imageNames, interval);
    }

    public void StartAnimation(IEnumerable<string> imageNames, 
        TimeSpan interval)
    {
        Storyboard storyboard = new Storyboard();
        ObjectAnimationUsingKeyFrames animation = 
            new ObjectAnimationUsingKeyFrames();
        storyboard.SetTarget(animation, image);
        storyboard.SetTargetProperty(animation, "Source");

        TimeSpan currentInterval = TimeSpan.FromMilliseconds(0);
        foreach(string imageName in imageNames)
        {
            ObjectKeyFrame keyFrame = new DiscreteObjectKeyFrame();
            keyFrame.Value = CreateImageFromAssets(imageName);
            keyFrame.KeyTime = currentInterval;
            animation.KeyFrames.Add(keyFrame);
            currentInterval = currentInterval.Add(interval);
        }

        storyboard.RepeatBehavior = RepeatBehavior.Forever;
        storyboard.AutoReverse = true;
        storyboard.Children.Add(animation);
        storyboard.Begin();
    }

    private static BitmapImage CreateImageFromAssets(string imageFilename)
    {
        return new BitmapImage(new Uri("ms=appx:///Assets/" + imageFilename));
    }
}
相關文章
相關標籤/搜索