分享一个 GIFControl 控件

2012/4/28:

其实 PictureBox 控件也支持显示GIF动画~~~ 哎!

源代码:

/* Create By Old At 2013/4/27
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace NetCoreLib.Win.Control
{
    public partial class GIFControl : UserControl
    {
        private Image m_Image = null;
        private EventHandler m_FrameChangedHandler = null;

        public GIFControl()
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            m_FrameChangedHandler = new EventHandler((s, e) => { this.Invalidate(); });
        }

        #region 控件属性

        [DefaultValue("")]
        [Localizable(true)]
        [Description("指定的GIF图片")]
        public Image GIFImage
        {
            get
            {
                return m_Image;
            }

            set
            {
                m_Image = value;
                if (m_Image != null)
                {
                    this.Width = m_Image.Width;
                    this.Height = m_Image.Height;
                }
            }
        }

        #endregion        

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (m_Image == null) { return; }

            if (ImageAnimator.CanAnimate(m_Image))
            {
                ImageAnimator.UpdateFrames(m_Image);
            }
            e.Graphics.DrawImage(m_Image, new Rectangle(0, 0, m_Image.Width, m_Image.Height));
        }
        
        public void BeginAnimate()
        {
            if (m_Image == null) { return; }

            if (ImageAnimator.CanAnimate(m_Image))
            {
                ImageAnimator.Animate(m_Image, m_FrameChangedHandler);
            }
        }

        public void StopAnimate()
        {
            if (m_Image == null) { return; }

            if (ImageAnimator.CanAnimate(m_Image))
            {
                ImageAnimator.StopAnimate(m_Image, m_FrameChangedHandler);
            }
        }
    }
}

使用方法:

添加控件到工具箱,拖动到待添加的窗体上并赋值 GIFImage 属性,选择加载一张GIF图片。

在窗体的Load事件中,记得调用 BeginAnimate() 方法;在窗体的 FormClosing事件中,记得调用 StopAnimate() 方法;

gifControl1.BeginAnimate();
gifControl1.StopAnimate();

 

 

你可能感兴趣的:(分享一个 GIFControl 控件)