CreateGraphics()方法和Paint事件参数

S.A*_*hid 5 c# gdi+

我已经阅读过CreateGraphics()将为我们做这些步骤的地方:

  1. 调用BeginPaint
  2. 画画
  3. 调用EndPaint

我的代码是这样的:

private void Form1_Load(object sender, EventArgs e)
{
    grFrom = this.CreateGraphics();
    grFrom.FillRectangle(Brushes.Red, this.ClientRectangle);
}
Run Code Online (Sandbox Code Playgroud)

没有红色矩形...但是,当我在下面复制行时Form1_paint,每个东西都正常运行.

grFrom.FillRectangle(Brushes.Red, this.ClientRectangle);
Run Code Online (Sandbox Code Playgroud)

所以,问题就在这里:什么是e.GraphicsForm1_paint

CreateGraphics还是e.Graphics

Ree*_*sey 6

两件事情:

  1. CreateGraphics为您提供了一个Dispose()在退出之前应始终使用的图形对象.您应该将您的语句放在using块中.
  2. 您绘制的图形仅在表单重新绘制之前有效.在你的情况下,通过在Form_Load中调用它,它发生在第一次渲染之前,并被"扔掉".你应该总是把它放在OnPaint()中,以使它在屏幕上"持久",因为这将导致重绘控件时重绘它.