我为此编写了一些代码。
AntialiasedText 函数将消除锯齿的文本绘制到离屏位图上。它计算透明度,以便使用AlphaBlend API 函数将文本与任何背景混合。
该函数后跟一个 WM_PAINT 处理程序,说明了它的用法。
// Yeah, I'm lazy...
const int BitmapWidth = 500;
const int BitmapHeight = 128;
// Draw "text" using the specified font and colour and return an anti-aliased bitmap
HBITMAP AntialiasedText(LOGFONT* plf, COLORREF colour, LPCWSTR text)
{
BITMAPINFO bmi = {0};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = BitmapWidth;
bmi.bmiHeader.biHeight = BitmapHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
LPBYTE pBits;
HBITMAP hDIB = CreateDIBSection(0, &bmi, DIB_RGB_COLORS, (LPVOID*)&pBits, 0, 0);
// Don't want ClearType
LOGFONT lf = *plf;
lf.lfQuality = ANTIALIASED_QUALITY;
HFONT hFont = CreateFontIndirect(&lf);
HDC hScreenDC = GetDC(0);
HDC hDC = CreateCompatibleDC(hScreenDC);
ReleaseDC(0, hScreenDC);
HBITMAP hOldBMP = (HBITMAP)SelectObject(hDC, hDIB);
HFONT hOldFont = (HFONT)SelectObject(hDC, hFont);
RECT rect = {0, 0, BitmapWidth, BitmapHeight};
FillRect(hDC, &rect, WHITE_BRUSH);
TextOut(hDC, 2, 2, text, wcslen(text));
// Flush drawing
GdiFlush();
// Calculate alpha
LPBYTE pixel = pBits;
int pixelCount = BitmapWidth * BitmapHeight;
BYTE r = GetRValue(colour);
BYTE g = GetGValue(colour);
BYTE b = GetBValue(colour);
for (int c = 0; c != pixelCount; ++c)
{
// Set alpha
BYTE alpha = 255 - pixel[0];
pixel[3] = alpha;
// Set colour
pixel[0] = b * alpha / 255;
pixel[1] = g * alpha / 255;
pixel[2] = r * alpha / 255;
pixel += 4;
}
SelectObject(hDC, hOldFont);
SelectObject(hDC, hOldBMP);
DeleteDC(hDC);
DeleteObject(hFont);
return hDIB;
}
这是一个WM_PAINT 处理程序来执行该功能。它两次绘制相同的文本,首先使用TextOut,然后使用抗锯齿位图。它们看起来差不多,但不如 ClearType。
case WM_PAINT:
{
LPCWSTR someText = L"Some text";
hdc = BeginPaint(hWnd, &ps);
LOGFONT font = {0};
font.lfHeight = 40;
font.lfWeight = FW_NORMAL;
wcscpy_s(font.lfFaceName, L"Comic Sans MS");
// Draw the text directly to compare to the bitmap
font.lfQuality = ANTIALIASED_QUALITY;
HFONT hFont = CreateFontIndirect(&font);
font.lfQuality = 0;
HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);
TextOut(hdc, 2, 10, someText, wcslen(someText));
SelectObject(hdc, hOldFont);
DeleteObject(hFont);
// Get an antialiased bitmap and draw it to the screen
HBITMAP hBmp = AntialiasedText(&font, RGB(0, 0, 0), someText);
HDC hScreenDC = GetDC(0);
HDC hBmpDC = CreateCompatibleDC(hScreenDC);
ReleaseDC(0, hScreenDC);
HBITMAP hOldBMP = (HBITMAP)SelectObject(hBmpDC, hBmp);
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.SourceConstantAlpha = 255;
bf.AlphaFormat = AC_SRC_ALPHA;
int x = 0;
int y = 40;
AlphaBlend(hdc, x, y, BitmapWidth, BitmapHeight, hBmpDC, 0, 0, BitmapWidth, BitmapHeight, bf);
SelectObject(hBmpDC, hOldBMP);
DeleteDC(hBmpDC);
DeleteObject(hBmp);
EndPaint(hWnd, &ps);
}
break;