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

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

string s = "This is my string"; 

我正在创建一个Telerik报告,我需要定义一个textbox ,它是我的字符串的宽度。 但是,size属性需要设置为Unit(Pixel,Point,Inch等)。 如何将我的字符串长度转换为Pixel,以便我可以设置宽度?

编辑:我已经尝试获取对图形对象的引用,但这是在inheritance自Telerik.Reporting.Report的类中Telerik.Reporting.Report

不使用控件或表单:

 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 
 Size textSize = TextRenderer.MeasureText("How long am I?", font); 

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

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

也取决于字体。 字符串长度不够。

您可以使用MeasureString()方法创建图形对象的实例。 但是您需要将字体名称,字体大小和其他信息传递给它。