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

Sco*_*ttG 26 c# telerik telerik-reporting

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

string s = "This is my string";
Run Code Online (Sandbox Code Playgroud)

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

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

Tom*_*son 61

不使用控件或表单:

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));
}
Run Code Online (Sandbox Code Playgroud)

或者在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
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,MeasureString应该是一个静态方法. (2认同)

Wac*_*urn 22

Size textSize = TextRenderer.MeasureText("How long am I?", font);
Run Code Online (Sandbox Code Playgroud)


shA*_*A.t 12

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

  • 我添加了一个看不见LabelAutoSize属性true- 脏工作 - .
  • 当我想要Width一个特定的字符串时,我将它设置为Label.Text.
  • WidthLabel会给我正确的值.

  • 兄弟那么聪明! (3认同)