Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically measure string pixel width in ASP.NET?

How do you get the size of a string? In Windows Forms it's easy, I just use graphics object and then MeasureString function. In ASP.NET I'm not sure how to do this.

like image 702
Troy Mitchel Avatar asked Apr 05 '11 14:04

Troy Mitchel


People also ask

How do you find the length of a string in pixels?

By their nature, strings do not have lengths in in pixels or something like that. Strings are data structures totally abstracted from the way they are presented, such as fonts, colors, rendering styles, geometrical sizes, etc. Those are all some properties of some UI elements, whatever they are.


1 Answers

The following method will provide the size of a String rendered in a given font:

private RectangleF sizeOfString(string text, Font font)
{
    GraphicsPath path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), new StringFormat());
    return path.GetBounds();
}

You could then use this to get the width as follows

float width = sizeOfString("Hello World", someFont).Width;
like image 50
Andrew Avatar answered Oct 16 '22 01:10

Andrew