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

守給你的承諾、 提交于 2019-12-10 12:39:03

问题


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;
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12479386/how-to-draw-text-with-transparent-background-using-c-winapi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!