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.
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. Similarly, you can also obtain a graphics object as a property of the PrintPageEventArgs when handling the PrintPage event for a PrintDocument.
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.
Create a Graphics object from any object that inherits from Image. This approach is useful when you want to alter an already existing image.
The following sections give details about each of these processes.
privatevoid Form1_Paint(object sender,
// Declares the Graphics object and sets it to the Graphics object// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
Bitmap myBitmap = new Bitmap(@"C:\Documents and
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.