什么时候调用 C# Draw/Fill 函数?如何从单独的 class 中调用它们?
When are C# Draw/Fill functions called? How can they be invoked from a separate class?
我不确定 Paint 表单生命周期是如何工作的,Form1_Paint
函数何时调用?如何控制它何时被调用?
我知道我可以像这样使用 C# 绘图库调用 Draw a Circle:
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
函数而不是在 运行 时间 运行 立即调用 .
有两种方法:
- 典型的方式是异步绘制。在任何 form/control 具有您的自定义绘图逻辑的地方调用
Invalidate
。该框架将在适当的时候引发 Paint
事件方法。
- 更有力的(non-recommended)方式是同步绘画。在你的 form/control 上调用
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
}
}
我不确定 Paint 表单生命周期是如何工作的,Form1_Paint
函数何时调用?如何控制它何时被调用?
我知道我可以像这样使用 C# 绘图库调用 Draw a Circle:
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
函数而不是在 运行 时间 运行 立即调用 .
有两种方法:
- 典型的方式是异步绘制。在任何 form/control 具有您的自定义绘图逻辑的地方调用
Invalidate
。该框架将在适当的时候引发Paint
事件方法。 - 更有力的(non-recommended)方式是同步绘画。在你的 form/control 上调用
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
}
}