动态GIF图片"/>
【转】在WPF显示动态GIF图片
原贴:.html
WPF
中是不支持直接预览GIF
图片的
<Image Source="1.gif"/>
上面这种用法是预览的GIF
图片是静止不动的。
通过使用WpfAnimatedGif
我们可以在WPF
应用程序中预览、控制GIF图片。
WpfAnimatedGif
的gitbub
地址
GitHub - XamlAnimatedGif/WpfAnimatedGif: A simple library to display animated GIF images in WPF, usable in XAML or in code.
WpfAnimatedGif
的使用方法
通过NuGet
引入包
xaml
中使用
- 声明xml命名空间
xmlns:gif=""
- 在
Image
控件中,使用ImageBehavior.AnimatedSource
代替Source
<Image gif:ImageBehavior.AnimatedSource="1.gif"/>
以下是完整代码:
<Window x:Class="Gif.GifWindow"xmlns=""xmlns:x=""xmlns:d=""xmlns:mc=""xmlns:local="clr-namespace:Gif"xmlns:gif=""mc:Ignorable="d"Title="GifWindow" Height="450" Width="800"><Grid><Image gif:ImageBehavior.AnimatedSource="1.gif"/></Grid>
</Window>
运行后就可以看到效果了。
如果想在设计状态下就看到效果,只需将ImageBehavior.AnimateInDesignMode
属性设置为true
可以在window元素中设置,控制整个window内部所有Image
控件
<Window x:Class="Gif.GifWindow"xmlns:gif=""gif:ImageBehavior.AnimateInDesignMode="True">
也可以在Image
元素内设置,只控制该元素
<Image gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.AnimateInDesignMode="True"/>
设置ImageBehavior.RepeatBehavior
属性控制播放行为
<!--播放3次-->
<Image gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.RepeatBehavior="3x"/><!--播放10秒-->
<Image gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.RepeatBehavior="0:0:10"/><!--永久播放-->
<Image gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.RepeatBehavior="Forever"/>
<object property="iterationCountx"/>-or-<object property="[days.]hours:minutes:seconds[.fractionalSeconds]"/>-or-<object property="[days.]hours:minutes"/>-or-<object property="days"/>-or-<object property="Forever"/>
该属性的默认值为0x
,表示使用GIF
图片自身的信息。
以上所有属性都支持使用绑定的方式设置。
代码中使用
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri("1.gif",UriKind.Relative);
image.EndInit();
WpfAnimatedGif.ImageBehavior.SetAnimatedSource(img, image);
<Image x:Name="img"/>
控制播放次数
// Repeat 3 times
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(3));// Repeat for 10 seconds
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(TimeSpan.FromSeconds(10)));// Repeat forever
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);
播放完成回调事件
<Image gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.RepeatBehavior="3x" gif:ImageBehavior.AnimationCompleted="Image_AnimationCompleted"/>
当播放次数为Forever
时,永远不会触发该事件。
手动控制播放、暂停、跳转到哪个画面
获取Image
控件的ImageAnimationController
var controller = ImageBehavior.GetAnimationController(imageControl);
// 暂停
controller.Pause();// 继续
controller.Play();// 跳转到最后一个画面
controller.GotoFrame(controller.FrameCount - 1);
你可能不想让图片自动播放,只需设置ImageBehavior.AutoStart
属性即可。
<Image x:Name="img" gif:ImageBehavior.AnimatedSource="1.gif" gif:ImageBehavior.AutoStart="False"/>
通过订阅CurrentFrameChanged
事件可以监听GIF
画面的改变
controller.CurrentFrameChanged += Controller_CurrentFrameChanged;
private void Controller_CurrentFrameChanged(object sender, EventArgs e)
{}
当animation
没有完全加载的时候,GetAnimationController
方法会返回null
,通过订阅AnimationLoaded
事件避免。
更多推荐
【转】在WPF显示动态GIF图片
发布评论