2017-02-08 45 views
-1

我不確定Paint表單生命週期是如何工作的,何時調用Form1_Paint函數?如何控制何時被調用?何時調用C#繪圖/填充函數?他們怎樣才能從一個單獨的課程中調用?

我知道我可以調用使用C#繪圖庫,像這樣畫了一個圈:

private void Form1_Paint(object sender, PaintEventArgs e) 
{ 
    e.Graphics.FillEllipse(Brushes.Red, new Rectangle(1, 1, 1, 1)); 
} 

如果我這樣定義的對象,因此:

class myCircleObject 
{ 
    int x, y, radius; 

    public myCircleObject(int x_val, int y_val, int r) 
    { 
     x = x_val; 
     y = y_val; 
     radius = r; 
    } 

    public void Draw() 
    { 
     System.Drawing.Rectangle r = new System.Drawing.Rectangle(x, y, radius, radius); 
     //Draw Circle here 
    } 
} 

,或者如果我不能做我怎樣才能調用Form1_Paint函數,而不是在運行時立即運行

+4

目前還不清楚[什麼問題(http://meta.stackexchange.com/q/66377/147640 ) 你正擁有的。 'Paint'事件是表單生命週期的一部分,它必須在那裏處理,然後使用提供的'Graphics'對象,其他任何東西都沒有意義。如果你想在處理'Paint'事件時使用你的類,一個選擇就是將'PaintEventArgs e'傳遞給它的'Draw'方法。如果您只是想在某個地方繪製某個地方,而不考慮表單生命週期,請從您的類中創建一個Graphics對象。 – GSerg

+0

爲你的函數添加一個參數:* public void Draw(Graphics thegraphics)*,然後* thegraphics.FillEllipse(Brushes.Red,r)* – Graffito

+0

我不知道你想要着色哪個像素。或者你爲什麼不想使用Paint事件.. ?? – TaW

回答

2

有兩種方式:

  • 的典型方法是異步作畫。請致電Invalidate在任何形式/控制您的自定義繪圖邏輯。該框架將在適當的時候提高Paint事件方法。
  • 更有力(不推薦)的方式是同步繪製。請在表單/控件上撥打Refresh,這會導致立即擡起Paint

例如(這是不完整的,但它說明了這個概念):

public class Form1 
{ 
    private MyCircle _circle; 

    private void Form1_Paint(object sender, PaintEventArgs e) 
    { 
     _circle.Draw(e); // this line causes the Circle object to draw itself on Form1's surface 
    } 

    public void MoveTheCircle(int xOffset, int yOffset) 
    { 
     _circle.X += xOffset; // make some changes that cause the circle to be rendered differently 
     _circle.Y += yOffset; 
     this.Invalidate(); // this line tells Form1 to repaint itself whenever it can 
    } 
} 
+0

如果我覺得我明白了我會說的問題:這正是他不想要的。但我真的不知道.. – TaW

+0

我認爲這是_is_什麼OP想要的。它看起來像OP試圖將繪圖代碼從Paint事件處理程序移出到每個處理特定類型工件的繪圖的類中。我確定OP知道如何以及何時更新他的圈子的屬性,但他不知道如何在重做之後導致重繪。 –

+0

@MichaelGunter這就是我正在尋找的唯一的問題是你會在'MyCircle.Draw'函數中做什麼。它會是'e.Graphics.FillEllipse(Brushes.Red,new Rectangle(1,1,1,1));'?我也編輯了這個問題,試圖說清楚。 – ryanmattscott

相關問題