1

我有一个使用另一个类的数据模板的字典,字典后面没有代码,只是 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 的最简单方法是什么?

多谢

4

1 回答 1

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从当前目录加载文件。

于 2013-07-08T15:03:22.380 回答