using System; using System.Drawing; using System.Drawing.Imaging; using System.Threading; using System.Windows.Forms; public class GifPlayer { private bool _playing = false; public bool Playing { get { return _playing; } set { _playing = value; if (value) { FrameDimension fd = new FrameDimension(Gif.FrameDimensionsList[0]); int framecount = Gif.GetFrameCount(fd); new Thread((ThreadStart)delegate { Graphics g = null; Host.Invoke((EventHandler)delegate { g = Host.CreateGraphics(); }); try { int i = 0; while (!(Host == null || Host.IsDisposed) && i < framecount && Playing) { Gif.SelectActiveFrame(fd, i); g.DrawImage(Gif, 0, 0); int delay = 100; for (int j = 0; j < Gif.PropertyIdList.Length; j++)//遍历帧属性 { if ((int)Gif.PropertyIdList.GetValue(j) == 0x5100)//.如果是延迟时间 { PropertyItem pItem = (PropertyItem)Gif.PropertyItems.GetValue(j);//获取延迟时间属性 byte[] delayByte = new byte[4];//延迟时间,以1/100秒为单位 delayByte[0] = pItem.Value[i * 4]; delayByte[1] = pItem.Value[1 + i * 4]; delayByte[2] = pItem.Value[2 + i * 4]; delayByte[3] = pItem.Value[3 + i * 4]; delay = BitConverter.ToInt32(delayByte, 0) * 10; //乘以10,获取到毫秒 break; } } Thread.Sleep(delay == 0 ? 100 : delay);//如果获取时间错误,默认100毫秒间隔 if (Loop && ++i >= framecount) i = 0; } } catch { return; } finally { g.Dispose(); } }).Start(); } } } public Control Host { get; set; } public Image Gif { get; set; } public bool Loop { get; set; } public GifPlayer(Control host, Image gif, bool loop) { if (host == null || gif == null) throw new NullReferenceException(); Host = host; Gif = gif; Loop = loop; Playing = true;//设置开始标记 } }
调用方法
GifPlayer gif_player = null; private void Form1_DoubleClick(object sender, EventArgs e) { if (gif_player != null) { gif_player.Playing = false; gif_player = null; } OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "gif|*.gif||"; if (dlg.ShowDialog() != DialogResult.OK) return; gif_player = new GifPlayer(this, Image.FromFile(dlg.FileName), true);//播放 //gif_player.Playing = false;//停止播放 }