如何在没有代码的情况下获得动画gif在WPF字典中工作?

时间:2013-07-08 12:33:19

标签: c# .net wpf animated-gif

我有一个使用另一个类的datatemplate的字典, 字典背后没有代码只是XAML

我需要有一个现场动画gif作为这本词典的一部分。

尝试这样做:

var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("myprojectname.Resources.theGifToUse.gif");
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
picturebox = image;

并在XAML中:

<WindowsFormsHost>
   <forms:PictureBox x:Name="pictu1rebox" Image="{Binding picturebox}"/>
</WindowsFormsHost>

但它不起作用!

最简单的方法是使用WpfAnimatedGif.dll吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

标准BitmapImage不支持播放.gif个文件。我知道的唯一选择是使用Bitmap。它有ImageAnimator。完整的例子:

XAML

<Window x:Class="PlayGifHelp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="MainWindow_Loaded">

    <Grid>
        <Image x:Name="SampleImage" />
    </Grid>
</Window>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    Bitmap _bitmap;
    BitmapSource _source;

    private BitmapSource GetSource()
    {
        if (_bitmap == null)
        {
            string path = Directory.GetCurrentDirectory();

            // Check the path to the .gif file
            _bitmap = new Bitmap(path + @"\anim.gif");
        }

        IntPtr handle = IntPtr.Zero;
        handle = _bitmap.GetHbitmap();

        return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _source = GetSource();
        SampleImage.Source = _source;
        ImageAnimator.Animate(_bitmap, OnFrameChanged);
    }

    private void FrameUpdatedCallback()
    {
        ImageAnimator.UpdateFrames();

        if (_source != null)
        {
            _source.Freeze();
        }

        _source = GetSource();

        SampleImage.Source = _source;
        InvalidateVisual();
    }

    private void OnFrameChanged(object sender, EventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));
    }
}

Bitmap不支持URI指令,因此我从当前目录加载.gif文件。