在项目中,需要用到播放gif图片,目前开源的gif控件推荐github上的WpfAnimatedGif,github源码地址为:
https://github.com/XamlAnimatedGif/WpfAnimatedGif
wiki 使用文档:
https://github.com/XamlAnimatedGif/WpfAnimatedGif/wiki
里面写的很详细,我这里挑主要的说明下:
1.引用,声明命名控件
<Window x:Class="WpfAnimatedGif.Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="http://wpfanimatedgif.codeplex.com">
2.在xaml界面上直接使用控件
<Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
3.控制gif的播放行为
<!-- Repeat 3 times -->
<Image gif:ImageBehavior.RepeatBehavior="3x"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
<!-- Repeat for 10 seconds -->
<Image gif:ImageBehavior.RepeatBehavior="0:0:10"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
<!-- Repeat forever -->
<Image gif:ImageBehavior.RepeatBehavior="Forever"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
4.vs设计模式预览gif
<Window x:Class="WpfAnimatedGif.Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="http://wpfanimatedgif.codeplex.com"
gif:ImageBehavior.AnimateInDesignMode="True">
5.代码使用-更改图片
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
6.代码使用-控制播放
var controller = ImageBehavior.GetAnimationController(imageControl);
// Pause the animation
controller.Pause();
// Resume the animation (or restart it if it was completed)
controller.Play();
// Go to the last frame
controller.GotoFrame(controller.FrameCount - 1);