如何在WIN32中查找字符串的宽度(以像素为单位)

Raz*_*zvi 17 c++ windows winapi

你能否在WIN32中更精确地测量字符串的宽度,而不是使用GetTextMetrics函数并使用tmAveCharWidth*strSize?

Nic*_*yer 22

尝试使用GetTextExtentPoint32.它使用给定设备上下文的当前字体来以逻辑单位测量呈现的字符串的宽度和高度.对于默认映射模式,MM_TEXT,1个逻辑单位是1个像素.

但是,如果您已更改当前设备上下文的映射模式,则逻辑单元可能与像素不同.您可以在MSDN上阅读有关不同映射模式的信息.使用映射模式,您可以将GetTextExtentPoint32返回的尺寸转换为像素.

  • GetTextExtentPoint32 使用“逻辑单位”;不是像素:http://msdn.microsoft.com/en-us/library/dd144938%28VS.85%29.aspx (2认同)
  • @用户 好收获。当映射模式为 MM_TEXT(默认)时,1 个逻辑单元 = 1 个像素,但这不一定是真的。我会修改我的答案。 (2认同)

Eva*_*ran 15

我不确定,但似乎:

HDC hDC = GetDC(NULL);
RECT r = { 0, 0, 0, 0 };
char str[] = "Whatever";
DrawText(hDC, str, strlen(str), &r, DT_CALCRECT);
Run Code Online (Sandbox Code Playgroud)

可能有用.

  • 这是一个比`GetTextExtentPoint32`更好的解决方案,因为它将映射模式排除在等式之外.作者需要改变的一件事是"DrawText"的标志.将其设置为`DT_CALCRECT | DT_NOPREFIX | DT_SINGLELINE`.然后可以将得到的宽度计算为`abs(r.right - r.left);` (4认同)

Kir*_*sky 5

图形::测量字符串

VOID Example_MeasureString(HDC hdc)
{
   Graphics graphics(hdc);
   // Set up the string.
   WCHAR string[] = L"Measure Text";
   Font font(L"Arial", 16);
   RectF layoutRect(0, 0, 100, 50);
   RectF boundRect;
   // Measure the string.
   graphics.MeasureString(string, 12, &font, layoutRect, &boundRect);
   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}
Run Code Online (Sandbox Code Playgroud)