2017-02-08 29 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

相关问题