WPF 应用 - WPF 播放 GIF 的两种方式

1. 使用 Winform 的 PictureBox

1.1 引用 dll

  • WindowsFormsIntegration.dll
  • System.Windows.Forms.dll
  • System.Drawing.dll

1.2 XMAl代码

<Window x:Class="TestGif.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:TestGif"
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <wfi:WindowsFormsHost>
        <winForms:PictureBox x:Name="PictureOfGif"></winForms:PictureBox>
    </wfi:WindowsFormsHost>
</Grid>
</Window>

1.3 后台代码

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    this.PictureOfGif.Image = System.Drawing.Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Resources/Images/TestImage/3.gif");
}

1.4 存在问题

如果窗口的 AllowsTransparency 为 true,会导致 PictureBox 出不来,
可以尝试在 wfi:WindowsFormsHost 外面包一层 Popup,并把 Popup 的 AllowsTransparency 设置为 false

2. 使用 WpfAnimatedGif

2.1 引用 dll

  • WpfAnimatedGif.dll
    可以通过 Nuget 安装或直接手动引用 dll

2.2 Xaml 代码

<Window
    ...
    xmlns:gif="http://wpfanimatedgif.codeplex.com"
    ...
    >
    
    <Image gif:ImageBehavior.AnimatedSource="/Resources/Images/TestImage/3.gif" />
/>
posted @ 2021-03-08 21:55  鑫茂  阅读(339)  评论(0编辑  收藏  举报