c three ways to create Graphics objects

  • 2020-05-10 18:44:20
  • OfStack

Method 1. Use PainEventArgs in the Paint event of the control or form

A reference to a graphics object is received in the Paint event of a form or control as part of PaintEventArgs (Graphics for which PaintEventArgs specifies the drawing control). This method is typically used to obtain a reference to a graphics object when creating the drawing code for the control.

Such as:

// form's Paint event response method


private void form1_Paint(object sender, PaintEventArgs e) 
{
    Graphics g = e.Graphics;
}

You can also override the OnPaint method of a control or form directly, as shown below:

protected override void OnPaint(PaintEventArgs e) 
{
    Graphics g = e.Graphics;
}

The Paint event occurs when the control is redrawn.

Method 2. Calls the CreateGraphics method of a control or form

Calls the CreateGraphics method of a control or form to get a reference to the Graphics object that represents the drawing surface of the control or form. This method is usually used if you want to draw on an existing form or control.

Such as:

Graphics g = this.CreateGraphics();

Method 3. Call the FromImage static method of the Graphics class

The Graphics object is created by any object inherited from Image. This method is usually used when you need to change an existing image.

Such as:


// Called" g1.jpg "Is located under the current path 
Image img = Image.FromFile("g1.jpg");// To establish Image object 
Graphics g = Graphics.FromImage(img);// create Graphics object 


Related articles: