CreateGraphics() Method and Paint Event Args

人盡茶涼 提交于 2019-12-23 10:49:30

问题


I have read somewhere that CreateGraphics() will do this steps for us :

  1. BeginPaint
  2. Drawing
  3. EndPaint

I have my code like this :

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

There is no red rectangle...but, When I copy line below in Form1_paint, every thing runs correctly.

grFrom.FillRectangle(Brushes.Red, this.ClientRectangle);

So Question is Here: What is the e.Graphics in Form1_paint?

CreateGraphics or e.Graphics?


回答1:


Two things:

  1. CreateGraphics gives you a graphics object that you should always Dispose() prior to exiting. You should put your statement inside of a using block.
  2. The graphics you draw are only valid until the form gets repainted. In your case, by calling this in Form_Load, it's happening prior to the first render, and getting "thrown away". You should always put this in OnPaint() in order to have it "persistent" on the screen, as that will cause it to get redrawn when the control is redrawn.



回答2:


Your form load call is drawing to the form, but then the first regular form paint event writes over it, so you never see it. (As this happens before your presented the form at all)

So Question is Here : What is the

e.Graphics in form1_paint ?

CreateGraphics or e.Graphics ?

I'm fairly sure the are equivilent, what you need is a better understanding of the windows forms event lifecycle.

This answer has relevant links: WinForms event life cycle




回答3:


You are creating a new graphics object, which is most likely backed by a memory buffer. The Graphics objects you get from e.Graphics is backed by a buffer which represents the screen area by the current window (window as in Window Handle, not a window with title bar, etc).

You can always bit blit the data from a created graphics object onto the one from e.Graphics.

I am sure someone will elaborate much more than I have.



来源:https://stackoverflow.com/questions/5352765/creategraphics-method-and-paint-event-args

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!