You can create a bitmap “on the fly” by creating a blank bitmap and then filling it in using GDI output functions. With this method, your application is not limited to external bitmap files, preloaded bitmap resources, or bitmaps that are hard-coded in your application source code.
Follow these general steps:
1.Create a blank bitmap by using the CreateCompatibleBitmap or CreateBitmap functions.
2.Select the bitmap into a memory device context using the SelectObject function.
3.Draw in the bitmap image using GDI output functions.
The following example creates a star-shaped bitmap by first making a bitmap that is compatible with the display, and then filling the compatible bitmap using the Polygon function:
HDC hDC;
HDC hMemoryDC;
HBITMAP hBitmap;
HBITMAP hOldBitmap;
POINT Points[5] = { 32,0, 16,63, 63,16, 0,16, 48,63 };
.
.
.
1 hDC = GetDC(hWnd);
2 hMemoryDC = CreateCompatibleDC(hDC);
3 hBitmap = CreateCompatibleBitmap(hDC, 64, 64);
4 hOldBitmap = SelectObject(hMemoryDC, hBitmap);
5 PatBlt(hMemoryDC, 0, 0, 64, 64, WHITENESS);
6 Polygon(hMemoryDC, Points, 5);
7 BitBlt (hDC, 0, 0, 64, hMemoryDC, 0, 0, SRCCOPY);
8 SelectObject(hMemoryDC, hOldBitmap);
DeleteDC(hMemoryDC);
9 ReleaseDC(hWnd, hDC);
In this example:
1 | The GetDC function retrieves a handle to the device context. The bitmap will be compatible with the display. (If you want a bitmap that is compatible with some other device, you should use the CreateDC function to retrieve a handle to that device.) |
2 | The CreateCompatibleDC function creates the memory device context in which the image of the bitmap will be drawn. |
3 | The CreateCompatibleBitmap function creates the blank bitmap. The size of the bitmap is set to 64 by 64 pixels. The actual number of bits in the bitmap depends on the color format of the display. If the display is a color display, the bitmap will be a color bitmap and might have many bits for each pixel. |
4 | The SelectObject function selects the bitmap into the memory device context and prepares it for drawing. The handle of the previously selected bitmap is saved in the variable hOldBitmap. |
5 | The PatBlt function clears the bitmap and sets all pixels white. This, or a similar function, is required since, initially, the image in a blank bitmap is undefined. You cannot depend on having a clean bitmap in which to draw. |
6 | The Polygon function draws the star by using the endpoints specified in the array of structures, Points. |
7 | The BitBlt function copies the bitmap from the memory device context to the display. |
8 | The SelectObject and DeleteDC functions restore the previous bitmap and delete the memory device context. Once the bitmap has been drawn, the memory device context is no longer needed. You cannot delete a device context when any bitmap other than the context's original bitmap is selected. |
9 | Finally, the ReleaseDC function releases the device context. The bitmap handle, hBitmap, may now be used in subsequent GDI functions. |