How do I get an animated gif to work in WPF?

前端 未结 18 1195
广开言路
广开言路 2020-11-22 12:16

What control type should I use - Image, MediaElement, etc.?

18条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 12:25

    Check my code, I hope this helped you :)

             public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)
                        {
        int ab=0;
                            var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                            var getFrames = gif.Frames;
                            BitmapFrame[] frames = getFrames.ToArray();
                            await Task.Run(() =>
                            {
    
    
                                while (ab < getFrames.Count())
                                {
                                    Thread.Sleep(speed);
    try
    {
                                    Dispatcher.Invoke(() =>
                                    {
                                        gifImage.Source = frames[ab];
                                    });
                                    if (ab == getFrames.Count - 1&&_Repeat)
                                    {
                                        ab = 0;
    
                                    }
                                    ab++;
                }
     catch
    {
    }
    
                                }
                            });
                        }
    

    or

         public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)
                {
     int ab = 0;   
                    var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                    var getFrames = gif.Frames;
                    BitmapFrame[] frames = getFrames.ToArray();
                    await Task.Run(() =>
                    {
    
    
                        while (ab < getFrames.Count())
                        {
                            Thread.Sleep(speed);
        try
        {
    
    
                         Dispatcher.Invoke(() =>
                            {
                                gifImage.Source = frames[ab];
                            });
                            if (ab == getFrames.Count - 1&&_Repeat)
                            {
                                ab = 0;
    
                            }
                            ab++;
        }
         catch{} 
    
    
    
                        }
                    });
                }
    

提交回复
热议问题