继承PictureBox显示GIF的自定义控件实现
处理GIF部分
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Drawing.Imaging; namespace AnimatePaint { /// <summary> /// 处理gif动画 /// </summary> public class AnimateImage { private Image _image; private FrameDimension _frameDimension; private bool _bCanAnimate; private int _iFrameCount = 1, _iCurrentFrame = 0; public event EventHandler OnFrameChanged; public Image Image { get { return _image;} } public bool CanAnimate { get { return _bCanAnimate;} } public int FrameCount { get { return _iFrameCount; } } public int CurrentFrame { get { return _iCurrentFrame; } } private void FrameChanged(object sender, EventArgs e) { _iCurrentFrame = _iCurrentFrame + 1 >= _iFrameCount ? 0 : _iCurrentFrame + 1; lock (_image) { _image.SelectActiveFrame(_frameDimension, _iCurrentFrame); if (OnFrameChanged != null) { OnFrameChanged(sender, e); } } } public AnimateImage(Image img) { _image = img; lock (_image) { _bCanAnimate = ImageAnimator.CanAnimate(_image); if (_bCanAnimate) { Guid[] guids = _image.FrameDimensionsList; _frameDimension = new FrameDimension(guids[0]); _iFrameCount = _image.GetFrameCount(_frameDimension); } } } public void Play() { if (_bCanAnimate) { lock (_image) { ImageAnimator.Animate(_image, new EventHandler(FrameChanged)); } } } public void Stop() { if (_bCanAnimate) { lock (_image) { ImageAnimator.StopAnimate(_image, new EventHandler(FrameChanged)); } } } public void Reset() { if (_bCanAnimate) { ImageAnimator.StopAnimate(_image, new EventHandler(FrameChanged)); lock (_image) { _image.SelectActiveFrame(_frameDimension, 0); _iCurrentFrame = 0; } } } } }
自定义控件部分
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace AnimatePicture { public partial class AnimatePictureBox : PictureBox { private AnimatePaint.AnimateImage _animateimg; private void image_OnFrameChanged(object sender, EventArgs e) { Invalidate(); } public AnimatePictureBox() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true); } public void LoadGIF(string strFileName) { _animateimg = new AnimatePaint.AnimateImage(Image.FromFile(strFileName)); _animateimg.OnFrameChanged += new EventHandler(image_OnFrameChanged); _animateimg.Play(); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); if (_animateimg != null) if (_animateimg.Image != null) lock (_animateimg.Image) { pe.Graphics.DrawImage(_animateimg.Image, new Point(0, 0)); } } } }