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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With