Saturday, May 26, 2007

Introduction to the GDI

The Device Context
Imagine you want to draw an orange. You can pick up a piece of stone and start drawing somewhere. If you draw on the floor, the next rain is likely to wipe your master piece away. If you draw on somebody's wall, you could face a law suit. Nevertheless, you realize that, to draw, you need at least two things besides your hands and your imagination: a platform to draw on and a tool to draw with.
As it happens, drawing in a studio and drawing on the computer have differences. To draw in real life, the most common platform is probably a piece of paper. Then, you need a pen that would show the evolution of your work. Since a pen can have or use only one color, depending on your goal, one pen may not be sufficient, in which case you would end up with quite a few of them. Since the human hand sometimes is not very stable, if you want to draw straight line, you may need a ruler. Some other tools can also help you draw geometric figures faster.
A device context is everything under one name. It is an orchestra, an ensemble of what need in order to draw. It includes the platform you draw on, the dimensioning of the platform, the orientation and other variations of your drawing, the tools you need to draw on the platform, the colors, and various other accessories that can complete your imagination.
When using a computer, you certainly cannot position tools on the table or desktop for use as needed. To help with drawing on the Windows operating system, Microsoft created the Graphical Device Interface, abbreviated as GDI. It is a set of classes, functions, variables, and constants that group all or most of everything you need to draw on an application. The GDI is provided as a library called Gdi.dll and is already installed on your computer.

Grabbing the Device Context
As mentioned already, in order to draw, you need at least two things: a platform and a tool. The platform allows you to know what type of object you are drawing on and how you can draw on it. On a Windows application, you get this platform by creating a device context.
A device context is actually a whole class that provides the necessary drawing tools to perform the job. For example, it provides functions for selecting the tool to use when drawing. It also provides functions to draw text, lines, shapes etc.
HDC: This is the most fundamental class to draw in your applications. It provides all of the primary functions used to perform the basic drawing steps. In order to use this class, first declare a variable from it. Then call the BeginPaint() function to initialize the variable using the PAINSTRUCT class. Once the variable has been initialized, you can use it to draw. After using the device context call the EndPaint() function to terminate the drawing.