This article
has been excerpted from book "GraphicsProgramming with GDI+".
We have already seen this in previous articles. We can override the onPaint
method by defining it as follows:
Protected
override void
OnPaint (PaintEventArgs args)
{
//Add
your drawing code here
}
Then we can use the Graphics property of PaintEventArgs to draw, lines, shapes,
text, and images. Listing 13.4 draws a few graphics shapes and text on our
form's OnPaint method. To test this code, create a Windows application and add
the code to it.
LISTING 13.4: Using OnPaint to draw
protected override
void OnPaint(PaintEventArgs
args)
{
//Get the Graphics object from
PaintEventArgs
Graphics g = args.Graphics;
//Draw rectangle
g.DrawRectangle(
new Pen(Color.Blue,
3),
new
Rectangle(10, 10, 50, 50));
//Fill ellipse
g.FillEllipse(
Brushes.Red,
new
Rectangle(60, 60, 100, 100));
//Draw text
g.DrawString("Text",
new Font("Verdana",
14),
new
SolidBrush(Color.Green),
200, 200);
}
Using Visual Studio .NET to add the Paint Event Handler
If you are using Visual Studio .NET, the easiest way to add a paint event
handler is to use the Properties windows of a form or control ad add a paint
event handler.
Disposing of Graphics Objects
It is usually good programming practice to dispose of objects when you're
finished using them. But it may not always be the best practice. A Graphics
object must always be disposed of it was created via the CreateGraphics method
or other "CreateFrom" methods. If we use a Graphics object on a paint event or
the OnPaint method from the PaintEventArgs.Graphics property, we do not have to
dispose of it.
NOTE
Do not dispose of Graphics objects associated with Windows controls such as
Button, ListBox, or DataGrid.
If you create objects such as pens and brushes, always dispose of them. Although
it is acceptable practice to rely on the garbage collector, doing so may often
be at the expense of application performance. Garbage collection can be a costly
affair because the garbage collector checks the memory for objects that haven't
been disposed of, and this process absorbs processor time. However, the Dispose
method of an object tells the garbage collector that the object is finished and
ready to be disposed of. Calling the Dispose method eliminates the need to have
the garbage collector check memory and thus saves processor time.
In Web pages, it is always food practice to dispose of objects as soon as they
are done being used.
The OnPaintBackground Method
The OnPaintBackground method paints the background of a control. This method is
usually overridden in the derived classes to handle the event without attaching
a delegate. Calling the OnPaintBackground method calls OnPaintBackground of the
base automatically, so we do not need to call it explicitly.