2013-03-16 68 views
3

我正在研究一個類似於ms paint的小繪畫程序。目前,我正在嘗試實現「選擇功能」。我面臨閃爍的問題,所以我做了一些研究,我發現,我應該創建自己的Panel類。雙面緩衝不適用於面板?

public class MyDisplay : Panel 
    { 
     public MyDisplay() 
     { 
      this.DoubleBuffered = true;    

      this.SetStyle(ControlStyles.UserPaint | 
       ControlStyles.AllPaintingInWmPaint | 
       ControlStyles.ResizeRedraw | 
       ControlStyles.ContainerControl | 
       ControlStyles.OptimizedDoubleBuffer | 
       ControlStyles.SupportsTransparentBackColor 
       , true); 

      this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
      this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
      this.UpdateStyles(); 
     } 
    } 

在主要形式有字段:

MyDisplay panel1 = new MyDisplay(); 
Graphics graphics1 = panel1.CreateGraphics(); 

我用3個事件在面板上:

  1. 的MouseDown - 我來到這裏點P1
  2. 的MouseMove - 這就是,在那裏我得到閃爍的問題,我打電話 graphics1.drawRectangle(...)graphics1.Clear()每次點擊鼠標移動
  3. MouseUp - 我只是最後一次繪製矩形。

這是怎麼回事?爲什麼我仍然面臨閃爍的問題,即使整個面板是白色的,只有1個矩形在那裏?謝謝。

編輯:

我已經重寫了OnPaint方法,但我仍然不知道下一步該怎麼做。

protected override void OnPaint(PaintEventArgs e) 
    { 
     // Call the OnPaint method of the base class. 
     base.OnPaint(e); 
     // Call methods of the System.Drawing.Graphics object. 
     e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle); 
    } 

EDIT2: 我應該畫上的位圖/圖像並重寫OnPaint方法來從那裏複製圖像並將其粘貼到面板?

+1

您正在使用CreateGraphics()銷燬雙緩衝功能。你必須**重寫OnPaint()方法來完成繪畫並避免閃爍。 – 2013-03-16 16:12:45

+0

你介意給我一些關於使用OnPaint的提示嗎?我不知道應該如何工作,我一直試圖找到谷歌沒有結果 – Patryk 2013-03-16 16:35:35

回答

1

刪除界定graphics1字段的行。

使用通過PaintEventArgs對象傳入的Graphics對象,在OnPaint的重寫中執行ALL繪畫。使用方法Invalidate(),Refresh()和Update()來控制從其他代碼重繪的時間。

回調如果您遇到此設計的任何特定困難。

+0

你能給我舉個例子嗎?我不知道它應該是什麼樣子,如果我想繪製矩形和圓形,我應該在OnPaint中放置2個這些方法嗎? – Patryk 2013-03-16 22:44:21

+0

我應該在位圖/圖像上繪製並覆蓋OnPaint方法以從中複製圖像並將其粘貼到面板上? – Patryk 2013-03-17 00:46:35

+0

在位圖上繪製並將位圖繪製到屏幕上通常都是從OnPaint方法完成的。 – 2013-03-17 02:56:53