今天需要做在winform窗口顯示並播放gif動畫圖片效果,網上找了找,並整理如下:

基本上都是使用RascallySnake的代碼:

測試時調用Loadgif()

#region 動畫

        //首先定義私有變量 
        private Image m_img = null;
        private EventHandler evtHandler = null;
        private int testx=100;
        int testy=100;
        //重載的當前winform的OnPaint方法,當界面被重繪時去顯示當前gif顯示某一幀
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (m_img != null)
            {
                //獲得當前gif動畫下一步要渲染的幀。
                UpdateImage();
                //將獲得的當前gif動畫需要渲染的幀顯示在界面上的某個位置。
                //注意此處,如果是要在panle1上繪製,需要修改為this.panle1.CreateGraphics();
                Graphics gfx = this.CreateGraphics();
                gfx.DrawImage(m_img, new Rectangle(testx, testy, m_img.Width, m_img.Height));
            }
        }

        //實現Load方法
        private void Loadgif()
        {
            //為委託關聯一個處理方法
            evtHandler = new EventHandler(OnImageAnimate);
            //獲取要加載的gif動畫文件
            m_img = Image.FromFile(Application.StartupPath + @"\well.gif");
            //調用開始動畫方法
            BeginAnimate();
        }
        //開始動畫方法
        private void BeginAnimate()
        {
            if (m_img != null)
            {
                //當gif動畫每隔一定時間後,都會變換一幀,那麼就會觸發一事件,該方法就是將當前image每變換一幀時,都會調用當前這個委託所關聯的方法。
                ImageAnimator.Animate(m_img, evtHandler);
            }
        }
        //委託所關聯的方法
        private void OnImageAnimate(Object sender, EventArgs e)
        {
            //該方法中,只是使得當前這個winfor重繪,然後去調用該winform的OnPaint()方法進行重繪)
            this.Invalidate();
        }
        //獲得當前gif動畫的下一步需要渲染的幀,當下一步任何對當前gif動畫的操作都是對該幀進行操作)
        private void UpdateImage()
        {
            ImageAnimator.UpdateFrames(m_img);
        }
        //關閉顯示動畫,該方法可以在winform關閉時,或者某個按鈕的觸發事件中進行調用,以停止渲染當前gif動畫。
        private void StopAnimate()
        {
            m_img = null;
            ImageAnimator.StopAnimate(m_img, evtHandler);
        }

        #endregion