You can create a bitmap “on the fly” by creating a blank bitmap and then filling it in by using GDI output functions. Using 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 function.
2.Select the bitmap into a memory device context by using the SelectObject function.
3.Draw the bitmap image by 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 by 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 };
hDC = GetDC(hWnd);
hMemoryDC = CreateCompatibleDC(hDC);
hBitmap = CreateCompatibleBitmap(hDC, 64, 64);
hOldBitmap = SelectObject(hMemoryDC, hBitmap);
PatBlt(hMemoryDC, 0, 0, 64, 64, WHITENESS);
Polygon(hMemoryDC, Points, 5);
BitBlt(hDC, 0, 0, 64, 64, hMemoryDC, 0, 0, SRCCOPY);
SelectObject(hMemoryDC, hOldBitmap);
DeleteDC(hMemoryDC);
ReleaseDC(hWnd, hDC);
In this example, the GetDC function retrieves a handle to the device context. The bitmap will be compatible with the screen. (If you want a bitmap to be compatible with some other device, you should use the CreateDC function to retrieve a handle of that device.)
The CreateCompatibleDC function creates the memory device context in which the image of the bitmap will be drawn. Following this, the CreateCompatibleBitmap function creates the blank bitmap, setting the size of the bitmap to 64 by 64 pixels. The number of bits in the bitmap depends on the color format of the screen. If the screen is a color screen, the bitmap will be a color bitmap and might have many bits for each pixel.
After the bitmap has been created, 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. The PatBlt function then clears the bitmap and sets all pixels to white. PatBlt, or a similar function, is required because the image in a blank bitmap is initially undefined. You cannot depend on having a clean bitmap to draw in.
The Polygon function draws the star by using the endpoints specified in the array of POINT structures, Points. The BitBlt function then copies the bitmap from the memory device context to the screen.
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.
Finally, the ReleaseDC function releases the device context. The bitmap handle hBitmap may now be used in subsequent GDI functions.