如何在WPF中使动态gif图像正常工作?

246

我应该使用哪种控件类型-ImageMediaElement等?


6
以下是最近这些解决方案的摘要。我使用的是VS2015进行实现。Dario提交的GifImage类很好用,但是我的一些gif出现了伪影。Pradip Daunde和nicael提供的MediaElement方法在预览区域可以工作,但是在运行时,我的所有gif都无法渲染。IgorVaschuk和SaiyanGirl的WpfAnimatedGif解决方案非常好且没有问题,但需要安装第三方库(显然)。我没有尝试其余的解决方案。 - Heath Carroll
21个回答

0
我有一些简单的解决方案,可以将动态GIF图像拆分为单独的帧。你只需要在一个新的类中传递图片列表即可:
class AniImage: Image
    {
        private Int32Animation ani = new Int32Animation(); 
        private List<Image> images; 
        public int duration { get; set; } 
        static FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata(new PropertyChangedCallback(ChangedCallbackMethod));
        public static readonly DependencyProperty frameProperty = DependencyProperty.Register("Frame", typeof(int), typeof(AniImage), metadata);
        static void ChangedCallbackMethod(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {            
            AniImage ai = (AniImage)d; 
            int curFrame = (int)e.NewValue; 
            ai.Source = ai.images[curFrame].Source; 
        }            
        public int Frame
        {
            get { return (int)GetValue(frameProperty); }
            set { SetValue(frameProperty, value); }
        }
        public AniImage(List<Image> imgs)
        {
            images = imgs; 
            duration = 2; 
            Frame = 0; 
            this.Source = imgs[0].Source;                
            if(images.Count > 1)
            {
                ani.From = 0;
                ani.To = images.Count - 1;
                ani.By = 1;
                ani.Duration = TimeSpan.FromSeconds(duration);
                ani.RepeatBehavior = RepeatBehavior.Forever;
                BeginAnimation(frameProperty, ani); 
            }           
        }
    }

创建新对象的方法如下:
        List<Image> imagesList = new List<Image>();
        string[] imgNames = {
            "Resources/spaceship021.gif",
            "Resources/spaceship022.gif",
            "Resources/spaceship023.gif",
            "Resources/spaceship024.gif",
            "Resources/spaceship025.gif" };

        foreach (string s in imgNames)
        {
            Image img = new Image();
            img.Source = new BitmapImage(new Uri(s, UriKind.Relative));
            imagesList.Add(img);
        }

        ship = new AniImage(imagesList);

        ship.Width = 100;
        ship.Height = 100;
        Canvas.SetLeft(ship, 250);
        Canvas.SetBottom(ship, 50);
        field.Children.Add(ship);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接