2011-07-19 75 views
0

所以我有一個用C#4.0編寫的Winforms應用程序中的自定義Button類。該按鈕通常會保存靜態圖像,但是當發生刷新操作時,它會切換爲動畫AJAX樣式的按鈕。爲了動畫化圖像,我設置了一個計時器,它可以在每個時間點上推進圖像動畫,並將其設置爲按鈕圖像。這是我能夠實現它的唯一方法。我擁有的解決方案並不那麼高效。任何意見將是有益的。在winforms按鈕中切換動畫圖像和靜態圖像

所以有兩個問題: 1.是否有一種更簡單的方法 - 因爲我忽略了我應該使用的某些功能? 2.有沒有更好的方法來手動動畫化圖像?

查找下面的代碼,瞭解我在每次打勾時所做的事情。第一個改進領域是:可能將圖像的每一幀複製到列表中?請注意_image.Dispose();無法處理本地圖像導致內存泄漏。

感謝您的任何建議。我會在網上發佈一些信息,並在我有一個有效的解決方案後連接它。

private void TickImage() 
    { 
     if (!_stop) 
     { 
      _ticks++; 

      this.SuspendLayout(); 

      Image = null; 

      if(_image != null) 
       _image.Dispose(); 

      //Get the animated image from resources and the info 
      //required to grab a frame 
      _image = Resources.Progress16; 
      var dimension = new FrameDimension(_image.FrameDimensionsList[0]); 
      int frameCount = _image.GetFrameCount(dimension); 

      //Reset to zero if we're at the end of the image frames 
      if (_activeFrame >= frameCount) 
      { 
       _activeFrame = 0; 
      } 

      //Select the frame of the animated image we want to show 
      _image.SelectActiveFrame(dimension, _activeFrame); 

      //Assign our frame to the Image property of the button 
      Image = _image; 

      this.ResumeLayout(); 

      _activeFrame++; 

      _ticks--; 
     } 
    } 

回答

2
  1. 我猜的WinForms沒有那麼在自己的動畫功能達到。如果您想要更高級的動畫,可以考慮使用一些第三方解決方案。
  2. 我想你不應該從資源中每次打勾加載圖片。更好的方法是預先加載圖像幀並保存參考。然後用它爲每個勾號設置適當的框架。

正如我最近測試過的,GIF動畫效果很好,沒有任何額外的編碼,至少在標準按鈕上。但是,如果你仍然需要手動氨化框,您可以嘗試這樣的事:

// put this somewhere in initialization 
private void Init() 
{ 
    Image image = Resources.Progress16; 
    _dimension = new FrameDimension(image.FrameDimensionsList[0]); 
    _frameCount = image.GetFrameCount(_dimension); 
    image.SelectActiveFrame(_dimension, _activeFrame); 
    Image = image; 
} 

private void TickImage() 
{ 
    if (_stop) return; 
    // get next frame index 
    if (++_activeFrame >= _frameCount) 
    { 
     _activeFrame = 0; 
    } 
    // switch image frame 
    Image.SelectActiveFrame(_dimension, _activeFrame); 
    // force refresh (NOTE: check if it's really needed) 
    Invalidate(); 
} 

另一種選擇是使用ImageList財產預裝的靜幀和週期ImageIndex屬性格式就像你上面SelectActiveFrame做到這一點。

+0

如何將圖像幀加載到列表中?我認爲這將解決我會遇到的任何主要表現問題。感謝您的回答。 –

+0

我已更新我的回答 –

+0

甜。當然,現在看起來真的很明顯。謝謝你的幫助。 –