Graphics Contexts and Graphics Objects

A C# graphics context represents a drawing surface that enables drawing on the screen. A Graphics object manages a graphics context by controlling how information is drawn. Graphics objects contain methods for drawing, font manipulation, color manipulation and other graphics-related actions. Every derived class of System.Windows.Forms.Form inherits a virtual OnPaint method in which most graphics operations are performed. The arguments to the OnPaint method include a PaintEventArgs object from which we can obtain a Graphics object for the Form. We must obtain the Graphics object on each call to the method, because the properties of the graphics context that the graphics object represents could change. Method OnPaint TRiggers the Control's Paint event.

When drawing on a Form, you can override method OnPaint to retrieve a Graphics object from argument PaintEventArgs or to create a new Graphics object associated with the appropriate surface. We demonstrate these drawing techniques in C# later in the chapter.

To override the inherited OnPaint method, use the following method header:

protected override void OnPaint( PaintEventArgs e )

Next, extract the incoming Graphics object from argument PaintEventArg, as in:

Graphics graphicsObject = e.Graphics;

Variable graphicsObject can now be used to draw shapes and strings on the form.

Calling the OnPaint method raises the Paint event. Instead of overriding the OnPaint method, programmers can add an event handler for the Paint event. Visual Studio .NET generates the Paint event handler in this form:

protected void MyEventHandler_Paint( object sender, PaintEventArgs e )

Programmers seldom call the OnPaint method directly, because drawing graphics is an event-driven process. An eventsuch as covering, uncovering or resizing a windowcalls the OnPaint method of that Form. Similarly, when any control (such as a TextBox or Label) is displayed, that control's OnPaint method is called.

You can force a call to OnPaint by calling a Control's Invalidate method. This method refreshes a control and implicitly repaints all its graphical components. Class Control has several overloaded Invalidate methods that allow programmers to update portions of a control.

Performance Tip 17 1

Calling the Invalidate method to refresh the Control can be inefficient if only a small portion of a Control needs refreshing. Calling Invalidate with a Rectangle parameter refreshes only the area designated by the rectangle. This improves program performance.

Controls, such as Labels and Buttons, do not have their own graphics contexts, but you can create them. To draw on a control, first create a graphics object by invoking the control's CreateGraphics method, as in:

Graphics graphicsObject = controlName.CreateGraphics();

Now you can use the methods provided in class Graphics to draw on the control.

Color Control

Категории