Drawing Graphics in C Sharp

From Techotopia
Revision as of 20:42, 28 January 2008 by Neil (Talk | contribs) (New page: The purpose of this chapter of C# Essentials is to provide the reader with a knowledge of teh basics of graphics drawing in C#. Drawing in C# is achieved using the '...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The purpose of this chapter of C# Essentials is to provide the reader with a knowledge of teh basics of graphics drawing in C#. Drawing in C# is achieved using the Graphics Object. The Graphics Object takes much of the pain out of graphics drawing by abstracting away all the problems of dealing with different display devices and screens resolutions. The C# programmer merely needs to create a Graphic Object and tell it what and where to draw.

Persistent Graphics

An important point to note before proceeding with is chapter is that simply creating a Graphics Object for a component and they drawing on that component does not create persistent graphics. In fact what will happen is that as soon as the window is minimized, or obscured by another window the graphics will be erased.

Fore this reason, steps need to be taken to ensure that any graphics are persistent. Two mechanisms for achieving this to perform the drawing in the Paint() event handler of the control, or to perform the drawing on a bitmap image in memory and then transfer that image to the component whenever the Paint() event is triggered (which occurs whenever the control is displayed or unobscured). We will look at both of this techniques in this chapter.

Creating a Graphics Object

The first step in this tutorial is to create a new Visual Studio project called CSharpGraphics. With the new project created select the Form in the design area and click on the lightning bolt at the top of the Properties panel to list the events available for the Form. Double click the Paint event to display the code editing page.

Graphics Objects are created by calling the CreateGraphics() method of the component on which the drawing is to performed. For example, a Graphics Object can be created on our Form called Form1 by calling CreateGraphics() method as follows in the Paint():