WPF中显示GIF图片

来源:互联网 发布:it管培生 编辑:程序博客网 时间:2024/05/22 06:43

WPF中显示GIF图片:
WPF很强大,但是他的Image控件却不支持GIF图片,只能显示第一帧。那么如何来显示GIF图片呢?以下有四种方法:
一、 第一种方法:使用MediaElement(实例中页面:DynamicImage1.xaml)
步骤:(实例页面:DynamicImage1.xaml)
1、 前台界面代码:

<MediaElement x:Name="element" LoadedBehavior="Play" Stretch="Fill"    Source="1.gif"                   MediaEnded="MediaElement_MediaEnded"/>

2、 Source路径注意需要设置
复制到输出目录:始终复制
生成操作:无

3、 在播放GIF时,GIF可能被中止,给MediaElement添加MediaEnded事件。

   ((MediaElement)sender).Position = ((MediaElement)sender).Position.Add(TimeSpan.FromMilliseconds(1));

当GIF停止播放时,将MediaElement的位置向后移动1毫秒来处理GIF播放停止问题。
4、 后台代码:

private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)       {        ((MediaElement)sender).Position = ((MediaElement)sender).Position.Add(TimeSpan.FromMilliseconds(1));     }

二、 第二种方法:引用WinForm中控件PictureBox(实例中页面:DynamicImage2.xaml)
步骤:
1、 向项目中的引用(reference)中添加两个动态库dll,一个是.NET库中的System.Windows.Forms,另外一个是WindowsFormsIntegration;
2、 添加完两个动态dll以后,就可以在控件库中找到WindowsFormsHost这个控件
3、 将这个控件放入窗体,放置完以后在xmal代码中会自动生成相应代码:

xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"       xmlns:WinFormControls="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

5、 这样就可以在WindowsFormsHost下放置需要的Windows Form控件了:

<WindowsFormsHost Grid.Column="1" Grid.Row="0">        <WinFormControls:PictureBox ImageLocation="1.gif" SizeMode="StretchImage"></WinFormControls:PictureBox>                  </WindowsFormsHost>      

6、 动态图片可以展示了

三、 第三种方法:使用自定义Image控件(实例:CSWPFAnimatedGIF)
(文件来源:https://code.msdn.microsoft.com/CSWPFAnimatedGIF-3029aeb9/sourcecode?fileId=26331&pathId=41660693)
步骤:
1、 定义类:CSWPFAnimatedGIF
2、 页面引用类文件:

xmlns:local="clr-namespace:CSWPFAnimatedGIF"

3、 前台显示控件:

<local:AnimatedGIFControl x:Name="GIFCtrl"/>

4、 Properties文件下Resources.resx的cs文件设置:

   internal static System.Drawing.Bitmap ProgressIndicator {            get {                object obj = ResourceManager.GetObject("ProgressIndicator", resourceCulture);                return ((System.Drawing.Bitmap)(obj));            }        }

5、 完成
四、 第四种方法:使用自定义GifImage控件
(本经验来源:http://www.cnblogs.com/zhouyinhui/archive/2007/12/23/1011555.html)
1. Gif解码器GifBitmapDecoder
public GifBitmapDecoder(Stream bitmapStream,BitmapCreateOptions createOptions, BitmapCacheOption cacheOption )
bitmapStream
类型: System.IO. Stream
要解码的位图流。
createOptions
类型: System.Windows.Media.Imaging. BitmapCreateOptions
位图图像的初始化选项。
cacheOption
类型: System.Windows.Media.Imaging. BitmapCacheOption
用于位图图像的缓存方法。

  1. 2
    解析GIF图片
    下面取出GIF每帧时间间隔等相关信息。
    GIF结构相关知识:wenku.baidu.com/link?url=slIFAaF4RSVB6jH4RJCKRjoCdU0fWBP3diaXI1t3tnpT3n52yf2b7UCvEt2mMs8OiWtgoSRYSHGzYQ3P7QJbgxCachUy7naTQ566U_uM_Di

  2. 3
    封装GifImage控件
    封装GifImage控件,继承自Image。

  3. 4
    使用GifImage控件



    DataGrid使用2.gif的引用方式为资源。

0 0
原创粉丝点击