Drawing a Color Bitmap

Since hard-coding a color bitmap may require considerable effort, it is usually simpler to create a compatible bitmap and draw in it. For example, to create a color bitmap that has a red, green, and blue plaid pattern, you simply create a blank bitmap and use the PatBlt function, with the red, green, and blue brushes, to draw the pattern. This method has the advantage of generating a reasonable bitmap even if the display does not support color. This is because GDI provides dithered brushes for monochrome displays when a color brush is requested. A dithered brush is a unique pattern of pixels that represents a color when that color is not available for the device.

The following statements create the color bitmap by drawing it:

# define PATORDEST0x00FA0089L

HDC hDC;

HDC hMemoryDC;

HBITMAP hBitmap;

HBITMAP hOldBitmap;

HBRUSH hRedBrush;

HBRUSH hGreenBrush;

HBRUSH hBlueBrush;

HBRUSH hOldBrush;

.

.

.

hDC = GetDC(hWnd);

hMemoryDC = CreateCompatibleDC(hDC);

hBitmap = CreateCompatibleBitmap(hDC, 64, 32);

hOldBitmap = SelectObject(hMemoryDC, hBitmap);

hRedBrush = CreateSolidBrush(RGB(255,0,0));

hGreenBrush = CreateSolidBrush(RGB(0,255,0));

hBlueBrush = CreateSolidBrush(RGB(0,0,255));

PatBlt(hMemoryDC, 0, 0, 64, 32, BLACKNESS);

hOldBrush = SelectObject(hMemoryDC, hRedBrush);

PatBlt(hMemoryDC, 0, 0, 24, 11, PATORDEST);

PatBlt(hMemoryDC, 40, 10, 24, 12, PATORDEST);

PatBlt(hMemoryDC, 24, 22, 24, 11, PATORDEST);

SelectObject(hMemoryDC, hGreenBrush);

PatBlt(hMemoryDC, 24, 0, 24, 11, PATORDEST);

PatBlt(hMemoryDC, 0, 10, 24, 12, PATORDEST);

PatBlt(hMemoryDC, 40, 22, 24, 11, PATORDEST);

SelectObject(hMemoryDC, hBlueBrush);

PatBlt(hMemoryDC, 40, 0, 24, 11, PATORDEST);

PatBlt(hMemoryDC, 24, 10, 24, 12, PATORDEST);

PatBlt(hMemoryDC, 0, 22, 24, 11, PATORDEST);

BitBlt(hDC, 0, 0, 64, 32, hMemoryDC, 0, 0, SRCCOPY)

SelectObject(hMemoryDC, hOldBrush);

DeleteObject(hRedBrush);

DeleteObject(hGreenBrush);

DeleteObject(hBlueBrush);

SelectObject(hMemoryDC, hOldBitmap);

DeleteDC(hMemoryDC);

ReleaseDC(hWnd, hDC);

In this example, the CreateSolidBrush function creates the red, green, and blue brushes needed to make the plaid pattern. The SelectObject function selects each brush into the memory device context as that brush is needed, and the PatBlt function paints the colors into the bitmap. Each color is painted three times, each time into a small rectangle. In this example, the application instructs PatBlt to overlap the different color rectangles a little. Since the PATORDEST raster-operation code is given, PatBlt combines the brush color with the color already in the bitmap by using a Boolean OR operator. The result is a different color border around each rectangle. After the bitmap is complete, BitBlt copies it from the memory device context to the screen.