How can I convert a string length to a pixel unit?

痞子三分冷 提交于 2019-11-26 18:10:00

问题


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?

EDIT: I have tried getting a reference to the graphics object, but this is done in a class that inherits from Telerik.Reporting.Report.


回答1:


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:

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



回答2:


Size textSize = TextRenderer.MeasureText("How long am I?", font);



回答3:


In this case, I usually use a dirty, but simple way:

  • I add an invisible Label that its AutoSize property is true -dirty work-.
  • When I want to have the Width for a specific string, I set it to the Label.Text.
  • The Width of the Label will give me the correct value.



回答4:


Depends on the font, too. String length isn't sufficient.




回答5:


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.



来源:https://stackoverflow.com/questions/451903/how-can-i-convert-a-string-length-to-a-pixel-unit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!