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

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

  •  18
  • Razvi  · 技术社区  · 17 年前

    5 回复  |  直到 17 年前
        1
  •  20
  •   Nick Meyer    13 年前

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

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

        2
  •  15
  •   Andreas buildpax    9 年前

    我不确定,但似乎:

    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    17 年前

    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    17 年前

    根据您的使用方式,您可以使用指定了DT_CALCRECT的DrawText,它将(对我来说总是相当准确)根据text/font/等计算所需矩形的大小。

        5
  •  0
  •   Stanislav Krasimirov Georgiev    10 年前

    对于Builder C++,首先动态创建新的TLabel,然后更改字体属性。将TLabel设置为自动大小。然后,您可以获得TLabel-width,它表示以像素为单位的字符串宽度。

     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");