Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 916
ScottG Avatar asked Jan 16 '09 20:01

ScottG


2 Answers

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 
like image 137
Tom Anderson Avatar answered Oct 26 '22 22:10

Tom Anderson


Size textSize = TextRenderer.MeasureText("How long am I?", font); 
like image 21
Wachburn Avatar answered Oct 26 '22 22:10

Wachburn