代码之家  ›  专栏  ›  技术社区  ›  Nifle Hassan Syed

如何确定给定字体的字符串大小

  •  16
  • Nifle Hassan Syed  · 技术社区  · 17 年前


    我很少需要显示很长的消息,我希望能够在需要时调整此表单的大小,以便此消息适合表单。

    S 将以字体呈现 F ?

    3 回复  |  直到 14 年前
        1
  •  19
  •   Dirk Vollmar    17 年前

    UseCompatibleTextRendering 相应的财产

    MeasureString

    string s = "A sample string";
    
    SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));
    

    TextRenderer 类别:

    SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
    

    见本文: Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls

        2
  •  5
  •   G S    17 年前

    这个怎么样:

    Size stringsize = graphics.MeasureString("hello", myFont);
    

    Here

        3
  •  1
  •   Pepe Alvarez    4 年前

    对于这个答案,我使用了一个helper函数:

    private static double ComputeSizeOfString(string text, string fontFamily, double fontSize)
    {
          System.Drawing.Font font = new(fontFamily,  (float)fontSize);
          System.Drawing.Image fakeImage = new System.Drawing.Bitmap(1, 1);
          System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(fakeImage);
          return graphics.MeasureString(text, font).Width;
    }
    

    因此,基本上,该方法使用一个尺寸为(1,1)的伪图像来计算字符串的长度,在本例中是根据所选文本创建的图像的宽度。

    string myTxt = "Hi there";
    double szs = ComputeSizeOfString(myTxt, "Georgia", 14);
    
        4
  •  0
  •   bernhardrusch    17 年前

    早在Win32中,我就为此使用了与VisualStyleRenderer::GetTextExtent等效的函数。