如何将 Gif 图像添加到 wpf
本文关键字:添加 wpf 图像 Gif | 更新日期: 2023-09-27 18:35:34
现在我正在开发一个带有WPF和C#的项目,其中一些部分与动画图像有关。那么每个人都可以告诉我如何添加.gif文件表格吗?谢谢。
这是一个完整的代码,您只需将下面的类包含在您的主要名称中即可。您的主要 WPF 表单是这样称呼它的,
<UI:AnimatedGIFControl x:Name="GIFCtrl" Visibility="Collapsed" VerticalAlignment="Center" Margin="200,0,0,0" Width="380" Height="48"/>
其中 UI 是定义 AnimatedGIFControl 的同名。您可以像这样称呼它
xmlns:UI="clr-namespace:xyz"
完整的类代码是 ,
class AnimatedGIFControl : System.Windows.Controls.Image
{
private Bitmap _bitmap; // Local bitmap member to cache image resource
private BitmapSource _bitmapSource;
public delegate void FrameUpdatedEventHandler();
/// <summary>
/// Delete local bitmap resource
/// Reference: http://msdn.microsoft.com/en-us/library/dd183539(VS.85).aspx
/// </summary>
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// Override the OnInitialized method
/// </summary>
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
this.Loaded += new RoutedEventHandler(AnimatedGIFControl_Loaded);
this.Unloaded += new RoutedEventHandler(AnimatedGIFControl_Unloaded);
}
/// <summary>
/// Load the embedded image for the Image.Source
/// </summary>
void AnimatedGIFControl_Loaded(object sender, RoutedEventArgs e)
{
// Get GIF image from Resources
if (Properties.Resources.ProgressIndicator != null)
{
_bitmap = Properties.Resources.ProgressIndicator;
Width = _bitmap.Width;
Height = _bitmap.Height;
_bitmapSource = GetBitmapSource();
Source = _bitmapSource;
}
}
/// <summary>
/// Close the FileStream to unlock the GIF file
/// </summary>
private void AnimatedGIFControl_Unloaded(object sender, RoutedEventArgs e)
{
StopAnimate();
}
/// <summary>
/// Start animation
/// </summary>
public void StartAnimate()
{
ImageAnimator.Animate(_bitmap, OnFrameChanged);
}
/// <summary>
/// Stop animation
/// </summary>
public void StopAnimate()
{
ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);
}
/// <summary>
/// Event handler for the frame changed
/// </summary>
private void OnFrameChanged(object sender, EventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new FrameUpdatedEventHandler(FrameUpdatedCallback));
}
private void FrameUpdatedCallback()
{
ImageAnimator.UpdateFrames();
if (_bitmapSource != null)
_bitmapSource.Freeze();
// Convert the bitmap to BitmapSource that can be display in WPF Visual Tree
_bitmapSource = GetBitmapSource();
Source = _bitmapSource;
InvalidateVisual();
}
private BitmapSource GetBitmapSource()
{
IntPtr handle = IntPtr.Zero;
try
{
handle = _bitmap.GetHbitmap();
_bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally
{
if (handle != IntPtr.Zero)
DeleteObject(handle);
}
return _bitmapSource;
}
}
并像这样使用
GIFCtrl.StartAnimate();
希望对您有所帮助。
不幸的是,
在 WPF Gif 动画中是不可见的。即使在图像控件中加载一个,也只能看到它的第一帧。
Image 不支持此功能,但使用自定义控件或包装 WinForms 控件的此重复答案上的一些解决方案似乎是很好的解决方案。