Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Painting Windows

The Win32 API includes a special message that is delivered to a window whenever it needs to be painted. This message is called WM_PAINT, and it serves as one of the main ways in which graphics are drawn to a window. A window might need to be repainted when the window is first created, when the window is uncovered from behind other windows, or for a variety of other reasons. The bottom line is that you must handle the WM_PAINT message in order to paint the inside (client area) of a window.

When I refer to painting or drawing to a window, I'm really referring to the client area of a window. This is the rectangular part of a window inside the window's border that doesn't include the window frame, caption, menu, system menu, or scrollbars. Figure 3.5 reveals how the coordinates of the client area begin in the upper-left corner of the window and increase down and to the right, as you learned earlier in the chapter. This coordinate system is very important because most GDI graphics operations are based on it.

Figure 3.5Figure 3.5 Most graphics in a Windows program are drawn to the client area of a window, which uses the Windows graphics coordinate system.

As you might recall, message handling takes place in the WndProc() function for a window. However, we were smart enough to make things simpler with the game engine you created in the previous chapter. More specifically, a WndProc() function is hidden in the game engine that handles the WM_PAINT message and calls the GamePaint() function. However, the call to the GamePaint() function is sandwiched between calls to the Win32 BeginPaint() and EndPaint() functions. This allows you to place graphics code in the GamePaint() function of your game without having to worry about obtaining a device context. The following is the WM_PAINT message handler in the WndProc() function, which shows how the GamePaint() function is called:

case WM_PAINT:
 HDC     hDC;
 PAINTSTRUCT ps;
 hDC = BeginPaint(hWindow, &ps);

 // Paint the game
 GamePaint(hDC);

 EndPaint(hWindow, &ps);
 return 0;

The device context obtained from BeginPaint() is passed into the GamePaint() function to delegate the specifics of drawing graphics to each individual game. The following is an example of a simple GamePaint() function:

void GamePaint(HDC hDC)
{
 *** GDI drawing operations go here ***
}

GDI painting operations are performed on a device context or DC, which is passed into the function via the hDC argument. The following is an example of drawing a line in the GamePaint() function:

void GamePaint(HDC hDC)
{
 MoveToEx(hDC, 0, 0, NULL);
 LineTo(hDC, 50, 50);
}

This code shows how to draw a line using GDI functions. You learn more about how these functions work in a moment, but first, let's take a look at how to draw text.

Painting Text

In Windows, text is treated no differently from graphics, which means that text is painted using GDI functions. The primary GDI function used to paint text is TextOut(), which looks like this:

BOOL TextOut(HDC hDC, int x, int y, LPCTSTR szString, int iLength);

The following are the meanings of the different arguments to the TextOut() function:

  • hDC—Device context handle

  • x—X coordinate of text position

  • y—Y coordinate of text position

  • szString—The string to be painted

  • iLength—Length of the string to be painted

The first argument to TextOut() is a handle to a device context, which is provided by the BeginPaint() function. All GDI functions require a handle to a device context, so you should get comfortable with seeing it in graphics code. The x and y arguments specify the position of the upper-left corner of the first string character relative to the client area (see Figure 3.6), whereas the last two arguments are a pointer to a string and the length of the string, in characters.

Figure 3.6Figure 3.6 Text is drawn at the upper-left corner of the first character with respect to the client area of a window.

The following is an example of how to use the TextOut() function to draw a simple string of text:

void GamePaint(HDC hDC)
{
 TextOut(hDC, 10, 10, TEXT("Michael Morrison"), 16);
}

Another text-related function that you might consider using is DrawText(), which allows you to draw text within a rectangle, as opposed to drawing it at a specified point. As an example, you can use DrawText() to center a line of text on the screen by specifying the entire client window as the rectangle in which to draw the text. The following is an example of using the DrawText() function in place of TextOut():

void GamePaint(HDC hDC)
{
 RECT rect;
 GetClientRect(hWindow, &rect);
 DrawText(hDC, TEXT("Michael Morrison"), -1, &rect,
  DT_SINGLELINE | DT_CENTER | DT_VCENTER);
}

In this example, the text is drawn centered both horizontally and vertically in the entire client area of the window. Notice that the length of the text string isn't necessary; this is because -1 is provided as the length, which means that the length should be automatically determined because the string is null-terminated. The flags in the last argument of DrawText() are used to determine how the text is drawn, which in this case, causes the text to be centered both horizontally and vertically.

Painting Primitive Graphics

Graphics primitives form a fundamental part of GDI and consist of lines, rectangles, circles, polygons, ovals, and arcs. You can create pretty impressive graphics by using these primitives in conjunction with each other. If you think graphics primitives sound somewhat limiting, keep in mind that some of the most enduring arcade games of all time were created solely through graphics primitives. Lunar Lander, Asteroids, Tempest, Gravitar, and Space Duel are a few of the classic vector arcade games whose graphics consisted solely of primitives.

The following are the major graphics primitives you can paint with GDI functions:

  • Lines

  • Rectangles

  • Ellipses

  • Polygons

The next few sections demonstrate how to draw each of these graphics primitives, along with how to use pens and brushes to add color to them.

Lines

Lines are the simplest of the graphics primitives and are therefore the easiest to draw. Lines are painted using the MoveToEx() and LineTo() functions, which set the current position and draw a line connecting the current position to a specified end point, respectively. The idea is that you use MoveToEx() to move the pen to a certain point and then use LineTo() to draw a line from that point to another point. You can continue to draw lines connecting points by calling LineTo() again. The following are what these functions look like:

BOOL MoveToEx(HDC hDC, int x, int y, LPPOINT pt);
BOOL LineTo(HDC hDC, int x, int y);

NOTE

An XY coordinate in Windows is referred to as a point and is often represented by the Win32 POINT structure. The POINT structure is used throughout Windows to represent coordinates for a variety of different operations. The POINT structure consists solely of two long integer fields, x and y.

Both functions accept a handle to a device context and an X and Y value for the point of the line. The MoveToEx() function also allows you to provide an argument to store the previous point. In other words, you can pass a pointer to a point as the last argument of MoveToEx() if you're interested in finding out the last point used for drawing. The following is an example of using MoveToEx() and LineTo() to draw a couple of lines:

void GamePaint(HDC hDC)
{
 MoveToEx(hDC, 10, 40, NULL);
 LineTo(hDC, 44, 10);
 LineTo(hDC, 78, 40);
}

In this code, the drawing position is first set by calling MoveToEx() and providing the XY position of a point. Notice that the final argument is passed as NULL, which indicates that you aren't interested in finding out the previous point. The LineTo() function is then called twice, which results in two connected lines being drawn.

Rectangles

Rectangles represent another type of graphics primitive that is very easy to draw. The Rectangle() function enables you to draw a rectangle by specifying the upper-left corner and the lower-right corner of the rectangle. The following is the prototype for the Rectangle() function, which helps to reveal its usage:

BOOL Rectangle(HDC hDC, int xLeft, int yTop, int xRight, int yBottom);

NOTE

To draw a perfect square using the Rectangle() function, just specify a rectangle that has an equal width and height.

The Rectangle() function is straightforward in that you pass it rectangular dimensions of the bounding rectangle for the rectangle to be painted. The following is an example of how to draw a couple of rectangles:

void GamePaint(HDC hDC)
{
 Rectangle(hDC, 16, 36, 72, 70);
 Rectangle(hDC, 34, 50, 54, 70);
}

There isn't really anything remarkable about this code; it simply draws two rectangles of differing sizes and positions. Don't forget that the last two arguments to the Rectangle() function are the X and Y positions of the lower-right corner of the rectangle, not the width and height of the rectangle.

Another handy rectangle function is FillRect(), which is used to simply fill a rectangular area with a particular color. The color used for the filling is determined by the brush passed into the function. The following is the prototype for the FillRect() function:

int FillRect(HDC hDC, CONST RECT *lprc, HBRUSH hbr);

Unlike the Rectangle() function, the FillRect() function accepts a pointer to a RECT structure instead of four separate rectangle values. You'll also notice that the FillRect() function accepts a brush handle as its third argument. The FillRect() function is put to good use later in the chapter when you build the Crop Circles example.

Ellipses

Although they are curved, ellipses are drawn in a manner very similar to rectangles. An ellipse is simply a closed curve, and therefore, it can be specified by a bounding rectangle. The circular explosions in the classic Missile Command game provide a very good example of a filled ellipse. Ellipses are painted using the Ellipse() function, which looks like this:

BOOL Ellipse(HDC hDC, int xLeft, int yTop, int xRight, int yBottom);

NOTE

To draw a perfect circle using the Ellipse() function, just specify a rectangle that has an equal width and height.

The Ellipse() function accepts the rectangular dimensions of the bounding rectangle for the ellipse to be painted. The following is an example of drawing an ellipse using the Ellipse() function:

void GamePaint(HDC hDC)
{
 Ellipse(hDC, 40, 55, 48, 65);
}

Not surprisingly, this code draws an ellipse based on four values that specify a bounding rectangle for the ellipse.

NOTE

Arcs, chords, and pies can also be drawn using Win32 GDI functions very similar to the Ellipse() function.

Polygons

The trickiest of graphics primitives is the polygon, which is a closed shape consisting of multiple line segments. The asteroid shapes in the popular Asteroids game offer a great example of polygons. Polygons are painted using the Polygon() function, which follows:

BOOL Polygon(HDC hDC, CONST POINT* pt, int iCount);

As you can see, the Polygon() function is a little more complex than the other graphics primitives functions in that it takes an array of points and the number of points as arguments. A polygon is painted by connecting each of the points in the array with lines. The following is an example of how to draw a polygon shape using the Polygon() function:

void GamePaint(HDC hDC)
{
 POINT points[3];
 points[0] = { 5, 10 };
 points[1] = { 25, 30 };
 points[2] = { 15, 20 };
 Polygon(hDC, points, 3);
}

The key to this code is the creation of the array of points, points, which contains three POINT structures. These three POINT structures are initialized with XY pairs, and the whole array is then passed into the Polygon() function, along with the total number of points in the array. That's all that is required to draw a polygon shape consisting of multiple line segments.

Working with Pens and Brushes

It's one thing to simply draw graphics primitives in their default mundane black and white style. It's quite another to control the line and fill colors of the primitives to get more interesting results. This is accomplished by using pens and brushes, which are standard GDI objects used in drawing graphics primitives. Whether you realize it or not, you're already using pens and brushes when you draw graphics primitives. It's just that the default pen is black, and the default brush is the same color as the window background.

Creating Pens

If you want to change the outline of a graphics primitive, you need to change the pen used to draw it. This typically involves creating a new pen, which is accomplished with the CreatePen() function:

HPEN CreatePen(int iPenStyle, int iWidth, COLORREF crColor);

The first argument is the style of the pen, which can be one of the following values: PS_SOLID, PS_DASH, PS_DOT, PS_DASHDOT, PS_DASHDOTDOT, or PS_NULL. All but the last value specify different kinds of lines drawn with the pen, such as solid, dashed, dotted, or a combination of dashed and dotted. The last value, PS_NULL, indicates that no outline is to be drawn; in other words, the pen doesn't draw. The second argument to CreatePen() is the width of the pen in logical units, which typically corresponds to pixels when drawing to the screen. The final argument is the color of the pen, which is specified as a COLORREF value. To help make things clear, the following is an example of how to create a solid blue pen that is one-pixel wide:

HPEN hBluePen = CreatePen(PS_SOLID, 1, RGB(0, 0, 255));

Keep in mind that simply creating a pen isn't enough to begin drawing with it. In a moment, you learn how to select a pen into a device context and begin drawing with it. However, let's first learn how to create brushes.

Creating Brushes

Although several different kinds of brushes are supported in the GDI, I'd like to focus on solid brushes, which allow you to fill in graphics shapes with a solid color. You create a solid brush using the Win32 CreateSolidBrush() function, which simply accepts a COLORREF structure. The following is an example of creating a purple brush:

HBRUSH hPurpleBrush = CreateSolidBrush(RGB(255, 0, 255));

Notice in this code that a value of 255 is used to set the red and blue components of the color, which is how you are achieving purple in the final mixed color; try out this color combination in Paint to see how it results in purple. Now that you have a handle to a brush, you're ready to select it into a device context and begin painting with it.

Selecting Pens and Brushes

In order to use a pen or brush you've created, you must select it into a device context using the Win32 SelectObject() function. This function is used to select graphics objects into a device context and applies to both pens and brushes. The following is an example of selecting a pen into a device context:

HPEN hPen = SelectObject(hDC, hBluePen);

In this example, the hBluePen you just created is selected into the device context. Also notice that the previously selected pen is returned from SelectObject() and stored in hPen. This is important because you will typically want to restore GDI settings to their original state when you're finished painting. In other words, you want to remember the original pen so that you can set it back when you're finished. The following is an example of restoring the original pen using SelectObject():

SelectObject(hDC, hPen);

Notice that it is no longer important to remember the return value of SelectObject() because you are restoring the original pen.

One more important task related to creating pens is that of deleting graphics objects that you create. This is accomplished with the DeleteObject() function, which applies to both pens and brushes. It is important to delete any graphics objects that you create after you've stopped using them and they are no longer selected into a device context. The following is an example of cleaning up the blue pen:

DeleteObject(hBluePen);

Selecting and deleting brushes is very similar to selecting and deleting pens. The following is a more complete example to illustrate:

HBRUSH hBrush = SelectObject(hDC, hPurpleBrush);
// *** Do some drawing here! ***
SelectObject(hDC, hBrush);
DeleteObject(hPurpleBrush);

In this example, the purple brush from the previous section is selected into the device context, some drawing is performed, and the old brush is restored. The purple brush is then deleted to clean up everything.

  • + Share This
  • 🔖 Save To Your Account