C# 如何将字符串长度转换为像素单位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/451903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a string length to a pixel unit?
提问by ScottG
I have a string like this:
我有一个这样的字符串:
string s = "This is my string";
I am creating a Telerik report and I need to define a textbox
that is the width of my string. However the size property needs to be set to a Unit (Pixel, Point, Inch, etc). How can I convert my string length into, say a Pixel so I can set the width?
我正在创建一个 Telerik 报告,我需要定义一个textbox
字符串的宽度。但是 size 属性需要设置为一个单位(像素、点、英寸等)。如何将我的字符串长度转换为像素,以便我可以设置宽度?
EDIT:I have tried getting a reference to the graphics object, but this is done in a class that inherits from Telerik.Reporting.Report
.
编辑:我尝试获取对图形对象的引用,但这是在继承自Telerik.Reporting.Report
.
采纳答案by Tom Anderson
Without using of a control or form:
不使用控件或表单:
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));
}
Or in VB.Net:
或者在 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
回答by Mitchel Sellers
You can create an instance of a graphics object an use the MeasureString()
method. But you will need to pass it the font name, font size, and other info.
您可以创建图形对象的实例并使用该MeasureString()
方法。但是您需要将字体名称、字体大小和其他信息传递给它。
回答by duffymo
Depends on the font, too. String length isn't sufficient.
也要看字体。字符串长度不够。
回答by Wachburn
Size textSize = TextRenderer.MeasureText("How long am I?", font);
回答by shA.t
In this case, I usually use a dirty, but simple way:
在这种情况下,我通常使用一种肮脏但简单的方法:
- I add an invisible
Label
that itsAutoSize
property istrue
-dirty work-. - When I want to have the
Width
for a specific string, I set it to theLabel.Text
. - The
Width
of theLabel
will give me the correct value.
- 我添加了一个无形的
Label
,它的AutoSize
属性是true
-肮脏的工作- 。 - 当我想要
Width
一个特定字符串时,我将它设置为Label.Text
. - 该
Width
的Label
会给我正确的值。