WPF中显示GIF图片
WPF中显示GIF图片
-
第一种是在WPF中内嵌WindowForm的PictureBox控件
需要引用System.Drawing、System.Windows.Forms和WindowsFormsIntegration。
<Window x:Class="WpfApp4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp4" mc:Ignorable="d" Loaded="Window_Loaded" Title="MainWindow" Height="450" Width="800"> <Grid> <WindowsFormsHost x:Name="host"> </WindowsFormsHost> </Grid> </Window>
后台代码
private void Window_Loaded(object sender, RoutedEventArgs e) { System.Windows.Forms.PictureBox pictureBox = new System.Windows.Forms.PictureBox(); this.host.Child = pictureBox; pictureBox.Image = new System.Drawing.Bitmap(@"C:\Users\Administrator\Pictures\timg6.gif");//文件路径 }
-
第二种是使用WpfAnimatedGif第三方组件来显示
通过Nuget安装WpfAnimatedGif。
示例代码如下:
<Window x:Class="WpfApp4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp4" xmlns:gif="http://wpfanimatedgif.codeplex.com" mc:Ignorable="d" Loaded="Window_Loaded" Title="MainWindow" Height="450" Width="800"> <Grid> <Image gif:ImageBehavior.AnimatedSource="timg7.gif" gif:ImageBehavior.AutoStart="True" gif:ImageBehavior.RepeatBehavior="Forever"/> </Grid> </Window>
-
第三种是使用MediaElement来播放,有一个局限就是图片路径必须是绝对路径,并且需要一点特殊处理来让gif能循环播放。
示例代码如下:
<Window x:Class="WpfApp4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp4" xmlns:gif="http://wpfanimatedgif.codeplex.com" mc:Ignorable="d" Loaded="Window_Loaded" Title="MainWindow" Height="450" Width="800"> <Grid> <MediaElement MediaEnded="MediaElement_MediaEnded" Source="C:\Users\Administrator\Pictures\timg6.gif"/> </Grid> </Window>
循环播放处理代码如下
private void MediaElement_MediaEnded(object sender, RoutedEventArgs e) { MediaElement mediaElement = sender as MediaElement; mediaElement.Position = mediaElement.Position.Add(TimeSpan.FromMilliseconds(1)); }