I'm trying to get the size of the text string using GetTextExtentPoint32. I read the documentation many times and do some research and as far as I know, the below code should give me the correct width
and height
of the text.
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.
Unfortunately, it doesn't give me the correct size. The width has too much for at least 10% and height is too much for at least 5%. To be exact, the result of width in the text of This is Text
is 228
and the height is 62
whereas the more accurate is somewhat near to 190 x 55
I think.
The text is painted using 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;
}
I'm thinking maybe it's somehow related to how I drew the text because, in the paint message, I used Font
instead of HFONT
. But that doesn't make any sense, right? As long as I set the correct font family and font size before GetTextExtentPoint32
then it should give me the exact width and height of the text. What do you think?