WPF 序列帧动画

直接上代码

private void LoadPics()
        {
            try
            {
                _storyboard = new Storyboard();
                for (int i = 0; i < 60; i++)
                {
                    ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames();
                    //ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri("pack://application:,,,/jg.CloudCube.WPF;component/Resources/LoadingAnimation/loading" + (i + 1) + ".png");
                    bitmap.CacheOption = BitmapCacheOption.Default;
                    bitmap.EndInit();

                    ImageBrush imgBrush = new ImageBrush(bitmap);
                    //读取图片文件
                    DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame();
                    //DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。
                    dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30));
                    //KeyTime 获取或设置应到达关键帧的目标 Value 的时间
                    //这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧
                    dokf.Value = imgBrush;
                    oauf.KeyFrames.Add(dokf);
                    Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)"));
                    //把动画应用到窗体的Rectangle中
                    Storyboard.SetTarget(oauf, RectDis);
                    //RectDis是Rectangle的名称
                    _storyboard.Children.Add(oauf);
                    //把ObjectAnimationUsingKeyFrames动画添加到Storyboard中
                }
                _storyboard.RepeatBehavior = RepeatBehavior.Forever;
            }
            catch (Exception ex)
            {
                var log = log4net.LogManager.GetLogger("Error");
                log.Error(ex.Message, ex);
            }
        }
 <Grid>
        <Rectangle Name="RectDis"/>
    </Grid>

播放动画时,使用Storyboard.Begin()方法就可以了。

猜你喜欢

转载自blog.csdn.net/technologyleader/article/details/84856231
今日推荐