Graphic Objects
| Overview | How Do I | Tutorial
Windows provides a variety of drawing tools to use in device contexts. It provides pens to draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object classes equivalent to the drawing tools in Windows. The table below shows the available classes and the equivalent Windows graphics device interface (GDI) handle types.
The general literature on programming for the Windows GDI applies to the Microsoft Foundation classes that encapsulate GDI graphic objects. This article explains the use of these graphic-object classes:
Classes for Windows GDI Objects
Class | Windows handle type |
HPEN | |
HBRUSH | |
HFONT | |
HBITMAP | |
HPALETTE | |
HRGN |
Each graphic-object class in the class library has a constructor that allows you to create graphic objects of that class, which you must then initialize with the appropriate create function, such as CreatePen.
Each graphic-object class in the class library has a cast operator that will cast an MFC object to the associated Windows handle. The resulting handle is valid until the associated object detaches it. Use the object’s Detach member function to detach the handle.
The following code casts a CPen object to a Windows handle:
CPen myPen;
myPen.CreateSolidPen( PS_COSMETIC, 1, RGB(255,255,0) );
HPEN hMyPen = (HPEN) myPen;
Process of Creating a Graphic Object in a Device Context
The following four steps are typically used when you need a graphic object for a drawing operation:
Define a graphic object on the stack frame. Initialize the object with the type-specific create function, such as CreatePen. Alternatively, initialize the object in the constructor. See the discussion of one-stage and two-stage creation, which provides example code.
Select the object into the current device context, saving the old graphic object that was selected before.
When done with the current graphic object, select the old graphic object back into the device context to restore its state.
Allow the frame-allocated graphic object to be deleted automatically when the scope is exited.
Note If you will be using a graphic object repeatedly, you can allocate it once and select it into a device context each time it is needed. Be sure to delete such an object when you no longer need it.