Myung Yoon
Myung Yoon

Reputation: 3

How do i Use Fillrect or DrawText on 32bit HBITMAP in C++

i'm sorry for what i did. i edited.

i'd like to use Fillrect on 32bit HBITMAP which is Created with CreateDIBSection

but i can't make rect visible in color that i want to. (i Drawed a fillrect with CreateSolidBrush blue(RGB(0, 0, 255)) on 32bit HBITMAP(hdcbmp), but it doesn't appear blue.)

here is source code

is there anyway to show rect color that i want to?

sorry for my poor english.

void DrawAlphaBitmap(HWND hWnd, ULONG uWidth, ULONG uHeight)
{
    BLENDFUNCTION  bf;
    HBITMAP        hbitmap;
    HBITMAP        hOldBitmap;
    BITMAPINFO     bmi;
    PVOID          pvBits;
    HDC            hdcwnd = GetDC(hWnd);
    HDC            hdcbmp = CreateCompatibleDC(hdcwnd);
    ZeroMemory(&bmi, sizeof(BITMAPINFO));
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = uWidth;
    bmi.bmiHeader.biHeight = uHeight;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;
    bmi.bmiHeader.biSizeImage = bmi.bmiHeader.biWidth *     bmi.bmiHeader.biHeight * 4;

    hbitmap = CreateDIBSection(hdcbmp, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x0);

    hOldBitmap = (HBITMAP)SelectObject(hdcbmp, hbitmap);
    bf.BlendOp = AC_SRC_OVER;
    bf.BlendFlags = 0;
    bf.SourceConstantAlpha = 0xff;
    bf.AlphaFormat = AC_SRC_ALPHA;

    RECT rc2 = { 100, 100, 200, 200 };
    FillRect(hdcbmp, &rc2, CreateSolidBrush(RGB(0, 0, 255)));

    AlphaBlend(hdcwnd, 0, 0, uWidth, uHeight, hdcbmp, 0, 0, uWidth, uHeight, bf);
    SelectObject(hdcbmp, hOldBitmap);
    DeleteObject(hbitmap);
    DeleteDC(hdcbmp);
    ReleaseDC(hWnd, hdcwnd);
}

Upvotes: -3

Views: 709

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31669

From documentation for BLENDFUNCTION:

AlphaFormat:
This flag is set when the bitmap has an Alpha channel (that is, per-pixel alpha).

In this case, alpha channel is not set. CreateDIBSection initializes the alpha values to zero. When AC_SRC_ALPHA is set, AlphaBlend ignores pixels whose alpha value is zero. Modify your code as follows:

//bf.AlphaFormat = AC_SRC_ALPHA; <- remove   
bf.AlphaFormat = 0; //replace with 0


Side note, you have resource leak in creation of HBRUSH handle. Change the code to

HBRUSH hbrush = CreateSolidBrush(RGB(0, 0, 255));
RECT rc2 = { 0, 0, w, h };
FillRect(memdc, &rc2, hbrush);
DeleteObject(hbrush);

Ideally, your function prototype should be void DrawAlphaBitmap(HDC hdc, ULONG uWidth, ULONG uHeight); so that HDC can be passed directly, for example from BeginPaint/EndPaint in WM_PAINT message.

Upvotes: 3

Related Questions