Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw text with transparent background using c++/WinAPI?

Tags:

c++

winapi

gdi

How to draw text with transparent color using WinAPI? In usual way I used SetBkMode(hDC, TRANSPARENT), but now I need to use double buffer. In this way images draws correct, but text draws not correct (with black background).

case WM_PAINT:
{
    hDC = BeginPaint(hWnd, &paintStruct);
    SetBkMode(hDC, TRANSPARENT);

    HDC cDC = CreateCompatibleDC(hDC);
    HBITMAP hBmp = CreateCompatibleBitmap(hDC, width, height);
    HANDLE hOld = SelectObject(cDC, hBmp);

    HFONT hFont = (HFONT)SelectObject(hDC, font);
    SetTextColor(cDC, color);
    SetBkMode(cDC, TRANSPARENT);

    TextOut(cDC, 0, 0, text, wcslen(text));

    SelectObject(cDC, hFont);

    BitBlt(hDC, 0, 0, width, height, cDC, 0, 0, SRCCOPY);

    SelectObject(cDC, hOld);
    DeleteObject(hBmp);
    DeleteDC(cDC);

    EndPaint(hWnd, &paintStruct);
    return 0;
}
like image 862
Alexander Avatar asked Sep 18 '12 14:09

Alexander


2 Answers

SetBkMode(dc, TRANSPARENT) should work fine still. Make sure you're using the correct DC handle when drawing to your back buffer.

like image 88
tenfour Avatar answered Nov 03 '22 02:11

tenfour


When you create a bitmap, the color isn't specified. The documentation doesn't state how it's initialized, but solid black (all zeros) seems likely. Since you're drawing the text on the bitmap, the background of the bitmap remains black. You then copy the entire bitmap to the DC and all the pixels come along, the background along with the text.

To fix this you must copy the desired background into the bitmap before you draw the text.

like image 35
Mark Ransom Avatar answered Nov 03 '22 04:11

Mark Ransom