2011-03-01 67 views
0

我有一個組件,一個繼承面板,其中我重寫OnPaint事件繪製一個500點的圖形。由於我需要在圖表上做一些選擇,因此閃爍。我發現這個DoubleBuffered屬性,但是當我將它設置爲True時,在面板構造函數中,圖形消失。我調試它,我發現繪圖方法仍然執行,但面板上沒有任何東西。 有誰知道爲什麼會發生這種情況?面板DoubleBuffered屬性停止繪圖,是不可見的

這是.NET 3.5 - C#。 WinForms應用程序

 try 
     { 
      Graphics g = e.Graphics; 

      //Draw _graphArea: 
      g.DrawRectangle(Pens.Black, _graphArea); 

      _drawingObjectList.DrawGraph(g, _mainLinePen, _diffLinePen, _dotPen, _dotBrush, _notSelectedBrush, _selectedBrush); 

      DrawSelectionRectangle(g); 

      g.Dispose(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

面板後裔構造:

 this.BackColor = Color.White; 
     this.SetStyle(ControlStyles.ResizeRedraw, true); 
     this.SetStyle(ControlStyles.UserPaint, true); 
     this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
     this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
     this.UpdateStyles(); 
+0

我認爲這是.Net?語言? – rene 2011-03-01 13:32:15

+0

@rene是的,它是。抱歉。 C#。這是現在的問題。 – elector 2011-03-01 13:55:12

+0

你能告訴我們你的繪圖代碼嗎? – FreeAsInBeer 2011-03-01 13:59:58

回答

1

嘗試使用ControlStyles.OptimizedDoubleBuffered代替。速度更快,通常效果更好。確保ControlStyles.AllPaintingInWmPaintControlStyles.UserPaint也被啓用。

現在,OnPaint()應該是唯一的窗口繪製的東西,這種方法只能從失效或使用Refresh();你絕不能自己撥打OnPaint()。不要處理Graphics對象。如果你失敗了這些情況,可能會出現閃爍和其他各種繪圖錯誤。

class MyControl : UserControl 
{ 
    public MyControl() 
    { 
     SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
     SetStyle(ControlStyles.UserPaint, true); 
     SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     e.Graphics.Clear(Color.Red); 
    } 

    void RandomEventThatRequiresRefresh(object sender, EventArgs e) 
    { 
     Refresh(); 
    } 
} 
+0

我正在做這一切。我使用this.Invalidate()來刷新圖形。但是,正如你在我的代碼中看到的,我不會在OnPaint中進行繪圖。我有其他的物體做繪圖。 – elector 2011-03-01 16:46:42

+1

@elector只要該方法是由'OnPaint'或一個被調用者調用的,並且您始終使用由事件處理程序提供給您的'e.Graphics'對象,就可以使用另一種方法進行繪製。看看是否刪除g.Dispose調用有幫助。我第一次看到這個問題時沒有注意到它。 – Coincoin 2011-03-01 16:54:26

+0

是的!刪除g.Dispose解決了它!我不知道爲什麼會出現這種情況,我從C#圖形書中學習了一些示例,這種代碼的安寧來自於此!謝謝 – elector 2011-03-01 20:44:59