新建GifImage类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Drawing;
namespace WPF_DCStation_ZTE
{
public class GifImage : System.Windows.Controls.Image
{
/// <summary>
/// gif动画的System.Drawing.Bitmap
/// </summary>
private Bitmap gifBitmap;
/// <summary>
/// 用于显示每一帧的BitmapSource
/// </summary>
private BitmapSource bitmapSource;
public GifImage(string path)
{
this.gifBitmap = new Bitmap(path);
this.bitmapSource = this.GetBitmapSource();
this.Source = this.bitmapSource;
}
/// <summary>
/// 从System.Drawing.Bitmap中获得用于显示的那一帧图像的BitmapSource
/// </summary>
/// <returns></returns>
private BitmapSource GetBitmapSource()
{
IntPtr handle = IntPtr.Zero;
try
{
handle = this.gifBitmap.GetHbitmap();
this.bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally
{
if (handle != IntPtr.Zero)
{
DeleteObject(handle);
}
}
return this.bitmapSource;
}
/// <summary>
/// Start animation
/// </summary>
public void StartAnimate()
{
ImageAnimator.Animate(this.gifBitmap, this.OnFrameChanged);
}
/// <summary>
/// Stop animation
/// </summary>
public void StopAnimate()
{
ImageAnimator.StopAnimate(this.gifBitmap, this.OnFrameChanged);
}
/// <summary>
/// Event handler for the frame changed
/// </summary>
private void OnFrameChanged(object sender, EventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
ImageAnimator.UpdateFrames(); // 更新到下一帧
if (this.bitmapSource != null)
{
this.bitmapSource.Freeze();
}
Convert the bitmap to BitmapSource that can be display in WPF Visual Tree
this.bitmapSource = this.GetBitmapSource();
Source = this.bitmapSource;
this.InvalidateVisual();
}));
}
/// <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)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteObject(IntPtr hObject);
}
}
窗体加载事件
或者使用相对路径
//string path = AppDomain.CurrentDomain.BaseDirectory + "Loading.gif";
private GifImage gifImage;
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
this.gifImage = new GifImage(@"E:\Work\WPF_demo\WPF_DCStation_ZTE\WPF_DCStation_ZTE\res\Loading.gif");//此处路径必须是绝对路径
this.gifImage.Width = 100;
this.gifImage.Height = 100;
label4.Content = this.gifImage;
}
//开始
private void button2_Click_1(object sender, RoutedEventArgs e)
{
gifImage.StartAnimate();
}
//停止
private void button3_Click(object sender, RoutedEventArgs e)
{
gifImage.StopAnimate();
}
效果展示