我有一个像这样的字符串:
string s = "This is my string";
我正在创建一个Telerik报告,需要定义一个与我的字符串宽度相同的textbox
。但是,宽度属性需要设置为单位(像素、点、英寸等)。我该如何将字符串长度转换为像素,以便设置宽度?
编辑:我尝试获取graphics对象的引用,但这是在继承自Telerik.Reporting.Report
类的类中完成的。
我有一个像这样的字符串:
string s = "This is my string";
我正在创建一个Telerik报告,需要定义一个与我的字符串宽度相同的textbox
。但是,宽度属性需要设置为单位(像素、点、英寸等)。我该如何将字符串长度转换为像素,以便设置宽度?
编辑:我尝试获取graphics对象的引用,但这是在继承自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
。Label
的Width
将给出正确的值。你可以创建一个图形对象的实例并使用MeasureString()
方法。但是你需要传递字体名称、字体大小和其他信息。
还要取决于字体。仅字符串长度是不足够的。
我编写了三个完全相同的函数,如下所示。只是为了让所有函数使用相同的名称而改变了签名。我将它们放在一个名为“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
只需使用您想要的任何一个(或为其他具有“文本”属性的控件编写更多内容)。
MeasureString
需要一个Graphics
,因为它考虑了当前图形变换。 - Ozgur OzcitakGraphicsUnit.Point
和GraphicsUnit.Pixel
不再是相同的大小。 - AaA