12

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;
}
Alexander
  • 275
  • 2
  • 4
  • 13

2 Answers2

18

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

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • I used this function for both DC, native, which I get by BeginBaint(...) and compatible, which I get by CreateCompatibleDC(...)... – Alexander Sep 18 '12 at 15:05
  • You need to use it for the same DC that you're drawing text to. Which text drawing API are you calling? Which kind of DC and bitmap are you drawing on? – tenfour Sep 18 '12 at 15:15
  • What I do: create compatible dc, create compatible bitmap, select object, setbkmode, draw(with compatible dc), bitblt, select object, delete object, delete dc. Images draws correct, but text draws with black background(( – Alexander Sep 18 '12 at 15:25
  • Maybe you should edit your question and provide minimal code which demonstrates the problem. It's just guessing at this point. – tenfour Sep 18 '12 at 15:28
3

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.

Marco A.
  • 43,032
  • 26
  • 132
  • 246
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • This way works) Not as I expected, but works. There are some regions with black background, but I think, I can fix them. Thanks! – Alexander Sep 18 '12 at 16:02