如何将字符串长度转换为像素单位?

29

我有一个像这样的字符串:

string s = "This is my string";

我正在创建一个Telerik报告,需要定义一个与我的字符串宽度相同的textbox。但是,宽度属性需要设置为单位(像素、点、英寸等)。我该如何将字符串长度转换为像素,以便设置宽度?

编辑:我尝试获取graphics对象的引用,但这是在继承自Telerik.Reporting.Report类的类中完成的。

6个回答

72

不使用控件或表单:

using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
{
    SizeF size = graphics.MeasureString("Hello there", new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point));
}

或者在 VB.Net 中:

Using graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
    Dim size As SizeF = graphics.MeasureString("Hello there", New Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point))
End Using

2
我认为MeasureString应该是一个静态方法。 - Kibbee
1
@Kibbee MeasureString需要一个Graphics,因为它考虑了当前图形变换。 - Ozgur Ozcitak
我相信 GraphicsUnit.PointGraphicsUnit.Pixel 不再是相同的大小。 - AaA

27
Size textSize = TextRenderer.MeasureText("How long am I?", font);

13

在这种情况下,我通常使用一种肮脏但简单的方法:

  • 我添加一个不可见的Label,它的 AutoSize 属性为true-肮脏的工作-。
  • 当我想要获取特定字符串的Width时,我将其设置为Label.Text
  • LabelWidth将给出正确的值。

4

你可以创建一个图形对象的实例并使用MeasureString()方法。但是你需要传递字体名称、字体大小和其他信息。


我有字体名称、大小等信息。我已经查看了MeasureString方法,但无法弄清如何创建Graphics对象引用。我没有窗体或控件,我只是在一个类中尝试解决这个问题。 - ScottG

4

还要取决于字体。仅字符串长度是不足够的。


1

我编写了三个完全相同的函数,如下所示。只是为了让所有函数使用相同的名称而改变了签名。我将它们放在一个名为“StringExtensions”的类中,并将每个函数声明为“Shared”,以便外部编码可以访问它们而不必创建类的实例变量。

  Public Shared Function TextLengthInPixels(oTextBox As TextBox, bTrim As Boolean) As Integer
      Return TextRenderer.MeasureText(IIf(bTrim, oTextBox.Text.Trim, oTextBox.Text), oTextBox.Font).Width
  End Function

  Public Shared Function TextLengthInPixels(oLabel As Label, bTrim As Boolean) As Integer
      Return TextRenderer.MeasureText(IIf(bTrim, oLabel.Text.Trim, oLabel.Text), oLabel.Font).Width
  End Function

  Public Shared Function TextLengthInPixels(oRTB As RichTextBox, bTrim As Boolean) As Integer
      Return TextRenderer.MeasureText(IIf(bTrim, oRTB.Text.Trim, oRTB.Text), oRTB.Font).Width
  End Function

只需使用您想要的任何一个(或为其他具有“文本”属性的控件编写更多内容)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接