How to: Create Graphics Objects for Drawing
Before you can draw lines and shapes, render text, or display and manipulate images with GDI+, you need to create a Graphics object. The Graphics object represents a GDI+ drawing surface, and is the object that is used to create graphical images.
There are two steps in working with graphics:
A graphics object can be created in a variety of ways.
To create a graphics object
Receive a reference to a graphics object as part of the PaintEventArgs in the Paint event of a form or control. This is usually how you obtain a reference to a graphics object when creating painting code for a control.
Call the CreateGraphics method of a control or form to obtain a reference to a Graphics object that represents the drawing surface of that control or form. Use this method if you want to draw on a form or control that already exists.
The following sections give details about each of these processes.
To obtain a reference to a Graphics object from the PaintEventArgs in the Paint event
To create a Graphics object with the CreateGraphics method
Call the CreateGraphics method of the form or control upon which you want to render graphics.
Dim g as Graphics ' Sets g to a Graphics object representing the drawing surface of the ' control or form g is a member of. g = Me.CreateGraphics
Graphics g; // Sets g to a graphics object representing the drawing surface of the // control or form g is a member of. g = this.CreateGraphics();
Additionally, you can create a graphics object from any object that derives from the Image class.
To create a Graphics object from an Image
The following example shows how to use a Bitmap object:
Bitmap myBitmap = new Bitmap(@"C:\Documents and Settings\Joe\Pics\myPic.bmp"); Graphics g = Graphics.FromImage(myBitmap);
You can only create Graphics objects from nonindexed .bmp files, such as 16-bit, 24-bit, and 32-bit .bmp files. Each pixel of nonindexed .bmp files holds a color, in contrast to pixels of indexed .bmp files, which hold an index to a color table.
The Pen class—Used for drawing lines, outlining shapes, or rendering other geometric representations.
The Brush class—Used for filling areas of graphics, such as filled shapes, images, or text.
The Font class—Provides a description of what shapes to use when rendering text.
The Color structure—Represents the different colors to display.