我有一个这样的字符串:
string s = "This is my string";
我正在创建一个 Telerik 报告,我需要定义一个textbox
字符串的宽度。但是,需要将 size 属性设置为单位(像素、点、英寸等)。如何将我的字符串长度转换为像素,以便我可以设置宽度?
编辑: 我尝试获取对图形对象的引用,但这是在继承自Telerik.Reporting.Report
.
我有一个这样的字符串:
string s = "This is my string";
我正在创建一个 Telerik 报告,我需要定义一个textbox
字符串的宽度。但是,需要将 size 属性设置为单位(像素、点、英寸等)。如何将我的字符串长度转换为像素,以便我可以设置宽度?
编辑: 我尝试获取对图形对象的引用,但这是在继承自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
.Width
。Label
MeasureString()
您可以使用该方法创建图形对象的实例。但是您需要将字体名称、字体大小和其他信息传递给它。
也取决于字体。字符串长度不够。