我正在尝试使用获取文本字符串的大小获取文本范围点32。我多次阅读文档并做了一些研究,据我所知,下面的代码应该给我正确的width
and height
的文本。
vFontFamily = "Segoe UI"; //font family
vFontSize = 26; //font size
HDC hdc = GetDC(hwnd);
HFONT hFont = CreateFont(
-MulDiv(vFontSize, GetDeviceCaps(hdc, LOGPIXELSY), 72), //calculate the actual cHeight.
0, 0, 0, // normal orientation
FW_NORMAL, // normal weight--e.g., bold would be FW_BOLD
false, false, false, // not italic, underlined or strike out
DEFAULT_CHARSET, OUT_OUTLINE_PRECIS, // select only outline (not bitmap) fonts
CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH | FF_SWISS, vFontFamily);
SIZE size;
HFONT oldfont = (HFONT)SelectObject(hdc, hFont);
GetTextExtentPoint32(hdc, L"This is Text", wcslen(L"This is Text"), &size);
width = size.cx; //get width
height = size.cy; //get height
SelectObject(hdc, oldfont); //don't forget to select the old.
DeleteObject(hFont); //always delete the object after creating it.
ReleaseDC(hwnd, hdc); //alway reelase dc after using.
不幸的是,它没有给我正确的尺寸。宽度过多至少 10%,高度过多至少 5%。准确地说,是文本中宽度的结果This is Text
is 228
高度是62
而更准确的是有点接近190 x 55
我认为。
文字是使用绘制的GDI+.
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
Graphics g(hdc);
FontFamily theFontFamily(vFontFamily);
Font font(&theFontFamily, vFontSize, FontStyleRegular, UnitPixel);
SolidBrush brush(Color(255, R, G, B));
PointF pointF(0.0f, 0.0f);
TextRenderingHint hint = g.GetTextRenderingHint(); // Get the text rendering hint.
g.SetTextRenderingHint(TextRenderingHintAntiAlias); // Set the text rendering hint to TextRenderingHintAntiAlias.
g.DrawString(L"This is Text", strlen("This is Text"), &font, pointF, &brush);
EndPaint(hwnd, &ps);
return TRUE;
}
我想这可能与我绘制文本的方式有关,因为在绘画消息中,我使用了Font
代替HFONT
。但这没有任何意义,对吧?只要我之前设置了正确的字体系列和字体大小GetTextExtentPoint32
那么它应该给我文本的确切宽度和高度。你怎么认为?