欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Winform 显示Gif图片的实例代码

程序员文章站 2024-02-26 09:26:58
复制代码 代码如下:using system;using system.collections.generic;using system.componentmodel;us...

复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.diagnostics;

namespace dysncpictest
{
    public partial class form1 : form
    {
        private image m_imgimage = null;
        private eventhandler m_evthdlanimator = null;
        public form1()
        {
            initializecomponent();
            this.setstyle(controlstyles.userpaint, true);
            this.setstyle(controlstyles.doublebuffer, true);
            this.setstyle(controlstyles.allpaintinginwmpaint, true);

            m_evthdlanimator = new eventhandler(onimageanimate);
            debug.assert(m_evthdlanimator != null);
        }

        protected override void onpaint(painteventargs e)
        {
            base.onpaint(e);
            if (m_imgimage != null)
            {
                updateimage();
                e.graphics.drawimage(m_imgimage, new rectangle(100, 100, m_imgimage.width, m_imgimage.height));
            }
        }

        protected override void onload(eventargs e)
        {
            base.onload(e);
            m_imgimage = image.fromfile("1.gif"); // 加载测试用的gif图片
            beginanimate();
        }

        private void form1_formclosing(object sender, formclosingeventargs e)
        {
             if (m_imgimage != null)
            {
                stopanimate();
                m_imgimage = null;
            }
        }

        private void beginanimate()
        {
           if (m_imgimage == null)
                return;

           if (imageanimator.cananimate(m_imgimage))
           {
                imageanimator.animate(m_imgimage,m_evthdlanimator);
           }
        }

        private void stopanimate()
        {
            if (m_imgimage == null)
                return;

            if (imageanimator.cananimate(m_imgimage))
            {
                imageanimator.stopanimate(m_imgimage,m_evthdlanimator);
            }
        }

        private void updateimage()
        {
            if (m_imgimage == null)
                return;

            if (imageanimator.cananimate(m_imgimage))
            {
                imageanimator.updateframes(m_imgimage);
            }
        }

        private void onimageanimate(object sender,eventargs e)
        {
            this.invalidate();
        }

        private void form1_load(object sender, eventargs e)
        {

        }
    }
}