1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
LPCTSTR lpTxt = _T("hello world");
//hdcWnd is the dc of the layered window
//Create temporary dc for the text
HDC hdcMem = CreateCompatibleDC(hdcWnd);
SetTextAlign(hdcMem, TA_LEFT | TA_TOP);
//Get the length and width of the text block
SIZE szTxt;
GetTextExtentPoint32(hdcMem, lpTxt, lstrlen(lpTxt), &szTxt);
//Create a bitmap
BITMAPINFOHEADER bih;
ZeroMemory(&bih, sizeof(BITMAPINFOHEADER));
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biPlanes = 1;
bih.biWidth = szTxt.cx;
bih.biHeight = szTxt.cy;
bih.biBitCount = 24;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biClrImportant = 0;
bih.biClrUsed = 0;
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(BITMAPINFO));
bi.bmiHeader = bih;
VOID *dibBitVal;
HBITMAP hTextBmp = CreateDIBSection(hdcMem, &bi, DIB_RGB_COLORS, &dibBitVal, NULL, NULL);
//Select into temporary dc
HBITMAP hOldMemBmp = (HBITMAP)SelectObject(hdcMem, hTextBmp);
//hdcImg is the DC i want the text to be drawn to
//Copy background and draw text over it
BitBlt(hdcMem, 0, 0, szTxt.cx, szTxt.cy, hdcImg, szWnd.cx / 2 - szTxt.cx / 2, 100, SRCCOPY);
SetBkMode(hdcMem, TRANSPARENT);
TextOut(hdcMem, 0, 0, lpTxt, lstrlen(lpTxt));
//Call AlphaBlend() to transfer image from temporary dc to target
BLENDFUNCTION bfAlpha;
bfAlpha.BlendFlags = 0;
bfAlpha.BlendOp = AC_SRC_OVER;
bfAlpha.AlphaFormat = AC_SRC_ALPHA;
bfAlpha.SourceConstantAlpha = 0xFF;
AlphaBlend(hdcImg, szWnd.cx / 2 - szTxt.cx / 2, 100, szTxt.cx, szTxt.cy, hdcMem, 0, 0, szTxt.cx, szTxt.cy, bfAlpha);
//Cleanup not shown here
|