2009-10-06 122 views
1

我在看一些GDI教程,但到目前爲止我發現的所有東西都和OnPaint方法一起使用,它將Paintarguments傳遞給Graphics。我還沒有找到從頭開始,我的意思是如何使用Graphics類本身? 這是整個代碼,我有TREID對我來說只是不工作:在OnPaint方法下畫一個橢圓

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; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      Pen pen= new Pen(Color.Red, 3); 
      Graphics g; 
      g = this.CreateGraphics(); 
    g.DrawEllipse(pen, 150, 150, 100, 100); 
     } 
    } 
} 

它只是不執行任何操作。我嘗試了新的形式,沒有任何東西。

預先感謝您!

+0

什麼是或沒有工作? – 2009-10-06 09:41:02

+0

當您調用CreateGraphics時,您必須手動處理創建的對象,即在完成處理時調用g.Dispose()。 – Skizz 2009-10-06 10:03:30

回答

1

該代碼可能是好的,它正在繪製一個橢圓,因爲你希望。但是,在Load事件之後,將顯示一個PaintBackground事件和一個PaintEvent,並顯示該窗體。默認情況下,PaintBackground將刪除控件的內容,從而有效地刪除剛繪製的橢圓。

繪畫是一個兩個階段的過程:

for each (region in set of regions that need updating) 
{ 
    PaintBackground (region) 
    Paint (region) 
} 

窗口管理器只重繪控制的需要更新的部分,如果控制的內容並沒有改變或任何用戶操作已經改變了控制的能見度,那麼沒有繪畫完成。

那麼,爲什麼要在Load方法中繪製橢圓呢?通常情況下,只需要在需要繪製東西時繪製某些東西,並在需要繪製PaintBackgroundPaint事件時告知表單。

你是否擔心閃爍?或者它是一個速度問題?橢圓很快畫出來。閃爍,但是,很難解決。您需要創建一個位圖,繪製位圖並在Paint事件期間將位圖傳輸給控件。另外,使PaintBackground事件不起作用 - 不會擦除控件,而是導致閃爍的擦除。

編輯:一個例子,我在這裏使用DevStudio 2005。

  1. 創建一個新的C#winform應用程序。
  2. 在Form1.cs添加以下內容:

    protected override void OnPaintBackground (PaintEventArgs e) 
    { 
        // do nothing! prevents flicker 
    } 
    
    protected override void OnPaint (PaintEventArgs e) 
    { 
        e.Graphics.FillRectangle (new SolidBrush (BackColor), e.ClipRectangle); 
    
        Point 
        mouse = PointToClient (MousePosition); 
    
        e.Graphics.DrawEllipse (new Pen (ForeColor), new Rectangle (mouse.X - 20, mouse.Y - 10, 40, 20)); 
    } 
    
    protected override void OnMouseMove (MouseEventArgs e) 
    { 
        base.OnMouseMove (e); 
        Invalidate(); 
    } 
    
  3. 編譯和運行。

+0

如果我需要使用輸入參數總是重繪一些特殊對象,該怎麼辦?我的表單是跟着鼠標。 – Petr 2009-10-06 10:06:59

+0

要跟隨鼠標,處理鼠標移動事件並使表單失效,這將導致控件在鼠標移動事件上重繪。 – Skizz 2009-10-06 10:21:44