Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

Chapter 4

Using GDI in MFC


Objectives
Understand GUI design and implementation. Understanding Graphics Device Context and Device Context Classes such as CDC, CPaintDC, CClientDC, CWindowDC, CMetaFileDC. Use of graphical objects from MFC for GUI. Use of GDI objects such as CPen, CBrush, CFont, CBitmap, CPalette, CRgn.

Introduction
Windows provides a graphical interface (GUI) to the underlying operating system and hardware. It also provides hardware information to the application through device contexts: data structures that are logical representations of the physical devices or virtual devices. MFC provides device context classes for general devices ( CDC), window client areas (CClientDC), total window area (CWindowDC), and window metafiles (CMetaFileDC) MFC also provides graphics objects used to draw on these device contexts. These graphics objects are pens (CPen), brushes ( CBrush), fonts (CFont), bitmap (CBitmap), and regions (CRgn). Because Windows provides a graphical User Interface ( GUI) to the underlying operating system and hardware, graphics are the mainstay of the Windows programs. This session explains how MFC packages and exposes device contexts and graphics objects. Graphics are extremely important in todays GUI OS world, and Windows is certainly no exception. This session explains the basic concepts of using graphics in Windows.

Device Contexts
CDC CPaintDC CClientDC CWindow CMetaFileDC

Device contexts are data structures, maintained by Windows, that provide a logical interface to a physical device. It allows device-independent drawing in Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile. Device context constraints the drawing area an application can use. For example, it limits painting to the region of the client window and ensures that an application cannot accidentally draw outside its frame window. Attempt to do otherwise are ignored by the device context. Four types of device contexts are supplied by the Win32 API: Display Contexts Supports graphics operations on a video display Information Contexts Provide for the retrieval of a device data. Memory Contexts Support graphics operations on a bitmap.

Page 48

Using GDI in MFC

Printer Contexts Support graphics operations on a printer or plotter. There are only five devices contexts available in the system; all applications in the system must share these five DCs.

CObject CObject CDC CDC CPaintDC CPaintDC CClientDC CClientDC CWindowDC CWindowDC CMetaFileDC CMetaFileDC

CDC
MFC provides a base class, called CDC, for outputting information to a device. CDC is the base class for all device context classes in MFC . CDC object provides member functions for working with device context such as a display or printer as well as member functions for working with a display context associated with the client area of the window. The class provides member functions for device-context operations, working with drawing tools, type-safe graphics device interface (GDI) object selection, and working with colors and palettes. It also provides member functions for getting and setting drawing attributes, mapping, working with the viewport, working with the window extent, converting coordinates, working with regions, clipping, drawing lines, and drawing simple shapes, ellipses, and polygons. Member functions are also provided for drawing text, working with fonts, using printer escapes, scrolling, and playing metafiles. To use a CDC object, the first task is to construct the object and then call its member functions to draw onto the device context. The CDC class has derived classes that can be used for drawing onto specific devices or for manipulating specific devices. The derived classes and the corresponding devices are listed below CDC Derived class CclientDC CpaintDC CwindowDC CMetaFileDC Drawing Area Client area of a window Invalid region of the client area Anywhere on the application window A file pseudo-device

SEED Infotech Ltd.

Using GDI in MFC

Page 49

CPaintDC
The CPaintDC class is derived from the CDC class. This object must be used when processing the WM_PAINT message. The basic steps to follow when using a CPaintDC object are given here: 1) 1.Create CPaintDC object. 2) 2.Draw on the CPaintDC object 3) 3.Destroy the CPaintDC object The CPaintDC constructor calls BeginPaint( ), and returns the paintDC to use for painting like wise, the destructor calls EndPaint( ). The following OnPaint function copies the coordinates of the bounding rectangle to a CRect object and then uses the CDC::Rectangle function to highlight the rectangle. CRect is the class MFC provides to represent rectangles. void CMainWindow :: OnPaint ( ) { CPaintDC dc( this); CRect rect =dc.m_ps.rcPaint; dc.Rectangle(rect); }

CClientDC
CClientDC creates a client-area device context that can be used outside OnPaint. Anytime an access is to be made to the client area of the window, this class needs to be referred. All drawing operations on the client area of the window are done through the member functions The following message handler uses CClientDC and two of its member functions to draw an X connecting the corners of the windows client area when the left mouse button is clicked void OnLButtonDown( UINT nFlags, CPoint point) { CRect rect; GetClientRect(&rect); CClientDC dc(this); dc.MoveTo( rect.left, rect.top); dc.LineTo( rect.right, rect.bottom); dc.MoveTo(rect.right, rect.top ); dc.LineTo( rect.left, rect.bottom); } MoveTo and LineTo are line-drawing functions that inherits from the CDC class.

CWindowDC
Frame windows are managed with class CWindowDC. MFC supplies the CWindowDC to automate the process of calling and releasing a device context representing the entire surface of the window, including both the client and the non-client areas. The Win32 API function GetDC ( ) is called the constructor of CWindowDC and the corresponding API function is called in the destructor. Using a CWindowDC object to draw a series of circles in response to WM_RBUTTONDOWN messages in the windows OnRButtonDown () message handler.

SEED Infotech Ltd.

Page 50

Using GDI in MFC

CMainWnd :: OnRButtonDown( UINT nFlags, CPoint point) { // Create a window DC to draw on CWindowDC dc (this); //Draw a series of ellipses on the DC in the windows NC title bar area. CRect rc; GetWindowRect(&rc); //get the title bar height. int cyCaption = GetSystemMetrics(SM_CYCAPTION); //define the ellipses bounding }

CMetaFileDC
A windows metafile is used to record and play back GDI function calls. This class has member functions to work with a metafile device context. It has two member functions of interest Create and Close. To create windows metafile first create the object of class CMetafile, and initialize it by calling the member function CMetafile::Create( ) .The prototype is BOOL Create( LPCTSTR lpszFilename = NULL); lpszFilename is a parameter points to a NULL terminated string specifying the filename of the metafile to create, if any. If no filename is provided, the method creates a new in-memory metafile. You can play metafile by calling CDC::PlayMetaFile( ) method with the metafile handle as a parameter.

Graphics Objects
Pens Brushes Fonts Bitmaps Palettes Regions

These windows tools are encapsulated by MFC graphics object classes. These classes are derived from CGdiObject. SDK Drawing Tool Pen MFC Class CPen Windows Data type HPEN HBRUSH

CObject CObject

Brush Font Font Palette Region

CGdiObject CGdiObject CBrush


CFont CBitmap CPalette CRgn

CPen CPen CBrush CBrush

HFONT HBITMAP HPALTTE

CFont CFont HRGN CBitmap CBitmap CPalette CPalette CRgn CRgn


SEED Infotech Ltd.

Using GDI in MFC

Page 51

The CGdiObject class of MFC is the base class for all GDI objects supported by MFC like Pen, Brush etc. An application will never create an object of this class, instead it will instantiated the classes derived from CGdiObject. The following four steps are typically followed when you need to make use of a graphic object for a drawing operation: Construct the graphic object. Call the type-specific Create function. Select the object into the current device context, the old graphic object that was used before need not be saved in MFC programs.

When finished using the current graphic object, select the old graphic object back into device context to restore its state Also ensure that the graphic object you created is deleted when you have finished using it. Do not attempt to delete an object currently selected in to the device context.

Note
If you are using a graphics object repeatedly, you can allocate it once and select it into a device context each time that it is needed. Also be sure to delete such an object when it is no longer needed. There are two ways of creating a graphic object: One-stage-construction Construct and initialize the object in one-stage, all with the constructor. Two-stage-construction Construct and initialize the object in two separate stages. The constructor allocates memory to the object and a separate initialization function, typically Create, initializes it.

CPen
The CPen class encapsulates the pen GDI object. Construction of CPen can be done in two ways one-stage construction and two-stage construction. In one-stage construction, the object is constructed by overloading the constructor, which is the object attributes are set at the time of creation itself. In two-stage construction there are two steps: 1) A pointer is assigned to the CPen class and with the C++ new operator, the CPen object is instantiated.
SEED Infotech Ltd.

Page 52

Using GDI in MFC

2) The CreatePen member function of the CPen is invoked, which then creates the Pen of the required style. The following code shows both methods of constructing a pen object: void CMyView::OnDraw( CDC* pDC ) { // One-stage CPen myPen1( PS_DOT, 5, RGB(0,0,0) ); // Two-stage: first construct the pen CPen myPen2; // Then initialize it if( myPen2.CreatePen( PS_DOT, 5, RGB(0,0,0) ) ) // Use the pen CPen *mypen3 mypen3 = new CPen(PS_DOT, 5, RGB(0,0,0)) // Use the pen } To use the pen to draw onto the device context, the pen that was created using any of the two methods is selected onto the device context with the CDC member function SelectObject. CMainWnd::OnRButtonDown( UINT nFlages,CPoint point) { // create a window DC to draw on CClientDC dc(this); //create a new red-dashed pen CPen penRed; penRed.CreatePen( PS_DASH, 1, RGB( 255,0,0) ); //select the new pen into the device context, and save the old pen to restore on clean up... CPen * ppenOld; ppenOld = dc.SelectObject(&penRed ); //draw a diamond on the DC CRect rc; GetClientRect(&rc); dc.MoveTo(o,(rc.bottom + rc.top)/2 ); dc.LineTo( rc.right +rc.left)/2,0 ); dc.LineTo( rc.right,(rc.bottom + rc.top)/2 ); dc.LineTo( (rc.right+rc.left)/2,rc.bottom); dc.LineTo(0,( rc.bottom +rc.top)/2 ); dc.SelectObject(&ppenOld); }

CBrush
The CBrush class encapsulates the functionality of a Windows graphics device interface (GDI) brush, which is a bitmap that is used to fill the interior of closed shapes. Brushes come in three basic varieties.

Brush Brush

Solid Solid Brush Brush


constructor

Hatch Hatch Brush Brush

Pattern Pattern Brush Brush

You can create a solid brush in one step by passing a COLORREF value to the CBrush

SEED Infotech Ltd.

Using GDI in MFC

Page 53

CBrush brush(RGB(255,0,0)); or CBrush brush; brush.CreateSolidBrush(RGB(255,0,0)); Hatch brushes are created by passing CBrushs constructor both a hatch index and a COLOREF value, or by calling CBrush::CreateHatchBrush. Like pens, brushes also comes in several styles and colors. CBrush ( int nIndex,COLORREF crColor);

where nIndex specifies the pattern of the brush, which can be any of the value as shown below.

Brush Style HS_BDIAGONAL HS_CROSS HS_DIAGONAL HS_FDIAGONAL HS_HORIZONTAL HS_VERTICAL

Description Downward hatch ( left to right) at 45 degrees Horizontal and vertical crosshatch Crosshatch at 45 degree Upward hatch (left to right) at 45 degrees Horizontal hatch Vertical hatch

CFont
A CFont object encapsulates a Windows GDI font and provides several methods for working for CFont object. The CFont class encapsulates a Windows graphics device interface (GDI) font and provides member functions for manipulating the font. To use a CFont object, construct a CFont object and attach a Windows font to it with CreateFont, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect, and then use the objects member functions to manipulate the font. You create a font to use when drawing text in device context. Font comes in thousand of typefaces and sizes. Windows GDI Fonts is typically created and attached to the CFont object.

CBitmap
The CBitmap class encapsulates a Windows graphics device interface (GDI) bitmap and provides member functions to manipulate the bitmap. A bitmap is an array of pixels that defines a graphic image -a picture a pattern. The colors of pixels are described by the data in the bitmap bits. To use a CBitmap object, construct the object, attach a bitmap handle to it with one of the initialization member functions, and then call the objects member functions.

CPalette
A palette is a windows GDI object that stores color information. A GDI palette object is basically a color lookup table used by the system to determine which colors to display on 256SEED Infotech Ltd.

Page 54

Using GDI in MFC

color palette display device. MFC encapsulates a windows color palette within the CPalette class. A palette provides an interface between an application and a color output device. The interface allows the application to take full advantage of the color capabilities of the output device without severely interfering with the colors displayed by other applications. Windows uses the applications logical palette (a list of needed colors) and the system palette (which defines available colors) to determine the colors used. A CPalette object provides member functions for manipulating the palette referred to by the object. Construct a CPalette object and use its member functions to create the actual palette, a graphics device interface (GDI) object, and to manipulate its entries and other properties.

CRgn
The CRgn class encapsulates a Windows graphics device interface (GDI) region. A region is an elliptical or polygonal area within a window. To use regions, you use the member functions of class CRgn with the clipping functions defined as members of class CDC. The member functions of CRgn create, alter, and retrieve information about the region object for which they are called.

SEED Infotech Ltd.

Using GDI in MFC

Page 55

Summary
Device-independent graphics have been made possible because of Device Contexts. Device context is a windows data structure that contains information about the drawing attributes of a device such as a display or a printer. CDC class is the base class provided by MFC for outputting to a device context, which outputs it to the device. Drawing in the client area of a window can be done with the CClientDC class data members and member functions. Windows provides variety of drawing tools to use in a device context. These includes Pen, Brush, Font etc. The CPen and CBrush classes and its member functions are used to create and manipulate pens and brushes.

QUIZ
1) 2) 3) 4) 5) What is a device context? Which is the base class for all types of device context? Which device context is used to draw anywhere on the application window? Which is the base class for all GDI objects? Which class encapsulates following GDI objects Pen, Brush, Font, Palette, Rgn and Bitmap.

SEED Infotech Ltd.

You might also like