代码之家  ›  专栏  ›  技术社区  ›  Razvi

如何在Win32中查找字符串的宽度(像素)

  •  16
  • Razvi  · 技术社区  · 15 年前

    您能在win32中比使用gettextmetrics函数和tmavecharwidth*strSize更精确地测量字符串的宽度吗?

    5 回复  |  直到 8 年前
        1
  •  20
  •   Nick Meyer    12 年前

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

    但是,如果更改了当前设备上下文的映射模式,则逻辑单元可能与像素不同。你可以读到 mapping modes on MSDN . 使用映射模式,可以将gettexxtextentpoint32返回的维度转换为像素。

        2
  •  15
  •   Andreas buildpax    8 年前

    我不确定,但似乎:

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

    可能奏效。

        3
  •  3
  •   Kirill V. Lyadvinsky    15 年前

    Graphics::MeasureString ?

    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);
    }
        4
  •  1
  •   DeusAduro    15 年前

    根据您使用的方式,您可以使用指定了dt_CalcRect的DrawText,它将(它总是为我做得相当精确)根据文本/字体等计算所需矩形的大小。

        5
  •  0
  •   Stanislav Krasimirov Georgiev    9 年前

    对于构造器C++,首先动态生成新的T标签,然后改变字体属性。将T标签设置为AutoSimple。然后你可以得到T标签宽度,女巫代表像素的字符串宽度。

     int WidthPixels (String font, int size, String text)
     {
        TLabel* label = new TLabel(Form1); // dynamic TLabel
        label->AutoSize = true;
        label->Font->Name = font; // your font
        label->Font->Size = size; // your font size
        label->Caption = text; // your string
        return label->Width;
     }
    
    int width = WidthPixels("Times New Roman", 19 , "Hey");