Windows Programming/GDI and Drawing

From Wikibooks, open books for an open world
Jump to: navigation, search

This page of the Windows Programming book is a stub. You can help by expanding it.


This page will talk about graphics and drawing using the windows GDI libraries.

Contents

[edit] Device Contexts

[edit] Brushes

Windows uses brushes to paint colors and fill areas with predefined patterns. Brushes have a minimum size of 8X8 pixels and like pens, have three basic characteristic: size, pattern and color. With their 8X8 pixel minimum size,brushes are said to have a pattern, not a style as pens do. The pattern may be a solid color, hatched, diagonal or any other user definable combination.

[edit] Pens

Pens are used to create borders around shapes you have drawn.

[edit] Basic Drawing

In Windows, drawing is typically handled by the WM_PAINT message. The following is an example of how to draw a red square:

case WM_PAINT:
{
        PAINTSTRUCT ps;
        BeginPaint(hwnd, &ps);
        
        RECT rectangle = {50, 50, 250, 250};
        HBRUSH hbr = CreateSolidBrush(RGB(125, 0, 0));
        
        FillRect(ps.hdc, &rectangle, hbr);
        
        DeleteObject(hbr);
        EndPaint(hwnd, &ps);
}
break;

Firstly, we create the PAINTSTRUCT variable ps. This is a data structure containing information about the painting operation. The next line calls BeginPaint. This initializes ps, then fills it with relevant information. For this example, we only need the hdc member of ps. This is a handle to our window's Device Context. Next, we create a rectangle. This holds the coordinates we're going to paint this rectangle at. The coordinates are relative to the upper-left corner of the window's client area. We also have to create a brush, otherwise Windows won't know what color to paint the rectangle. Finally, we call FillRect, and pass the parameters ps.hdc, a pointer to rectangle, and hbr, our brush. This paints the rectangle directly to our window's device context, and from there it is painted on the screen. After every painting operation, it is necessary to clean up any GDI objects we use, in this case hbr and ps.

[edit] Metafiles

[edit] Next Chapter

Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export