Roman Kwaśniewski
Roman Kwaśniewski

Reputation: 483

Creating a new bitmap with given dimensions filled with given color

I'm creating a program using the Win32 API, and I need to create a new bitmap filled with one color and with given dimensions.

Here is my code:

m_hBitmap =( HBITMAP ) CreateCompatibleBitmap(hDC, iWidth, iHeight);

HDC hDCn = CreateCompatibleDC( hDC );
SelectObject( hDCn, m_hBitmap );

ExtFloodFill(hDCn, 0, 0, crColor, FLOODFILLSURFACE);

DeleteDC( hDCn );

The bitmap dimensions match, but the bitmap is always black regardless of the crColor parameter.

Upvotes: 1

Views: 866

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598384

Use FillRect() instead of ExtFloodFill().

Also, you need to de-select the bitmap before you delete the DC, otherwise the original bitmap created and selected into the DC by CreateCompatibleDC() will be leaked.

Try this:

m_hBitmap = CreateCompatibleBitmap(hDC, iWidth, iHeight);

HDC hDCn = CreateCompatibleDC(hDC);
HBITMAP hOld = (HBITMAP) SelectObject(hDCn, m_hBitmap); // <-- SAVE OLD BITMAP! 

//ExtFloodFill(hDCn, 0, 0, crColor, FLOODFILLSURFACE);
RECT r;
r.left = r.top = 0;
r.right = iWidth;
r.bottom = iHeight;
HBRUSH hBrush = CreateSolidBrush(crColor);
FillRect(hDCn, &r, hBrush);
DeleteObject(hBrush);

SelectObject(hDCn, hOld); // <-- RESTORE OLD BITMAP
DeleteDC(hDCn);

Upvotes: 3

Related Questions