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

How to draw text with transparent color using WinAPI? Usually I used SetBkMode (hDC, TRANSPARENT), but now I need to use a double buffer. Thus, the images are drawn correctly, but the text does not draw correctly (with a 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; } 
+6
source share
2 answers

When creating a raster image, color is not specified. The documentation does not indicate how it is initialized, but solid black (all zeros) seems likely. As you draw text on a bitmap, the background of the bitmap remains black. Then you copy the entire bitmap to DC, and all the pixels go together, the background along with the text.

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

+2
source

SetBkMode(dc, TRANSPARENT) should work fine. Make sure you use the correct DC grip when drawing into the rear buffer.

+8
source

Source: https://habr.com/ru/post/925673/


All Articles