【问题标题】:How to determine the size of a string given a font如何确定给定字体的字符串的大小
【发布时间】:2010-10-17 19:06:05
【问题描述】:

我有一个显示一些进度信息的小表单。
我很少需要显示相当长的消息,并且我希望能够在需要时调整此表单的大小,以便此消息适合表单。

那么我如何找出字符串S 将以F 字体呈现的宽度?

【问题讨论】:

    标签: c# .net winforms fonts


    【解决方案1】:

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

    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) 的 fakeimage 来计算字符串的长度,在本例中是根据您选择的文本创建的图像的宽度。

    如何使用它的示例如下所示:

    string myTxt = "Hi there";
    double szs = ComputeSizeOfString(myTxt, "Georgia", 14);
    

    【讨论】:

      【解决方案2】:

      这取决于所使用的渲染引擎。您基本上可以在 GDI 和 GDI+ 之间切换。可以通过相应地设置@987654321@属性来完成切换

      当使用 GDI+ 时,你应该使用MeasureString:

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

      当使用 GDI(即原生 Win32 渲染)时,您应该使用 TextRenderer 类:

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

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

      【讨论】:

      • 如果您使用的是 WPF 并且需要一个变量 FontSize,请确保从像素转换为点 points = (pixels * (72.0 / 96.0))
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        这个怎么样:

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

        Here 是 MSDN 链接。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-11
          • 2016-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-26
          • 1970-01-01
          相关资源
          最近更新 更多