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

Troy Mitchel picture Troy Mitchel · Apr 5, 2011 · Viewed 14.3k times · Source

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.

Answer

Eystein Bye picture Eystein Bye · Sep 28, 2012

Like Tom Gullen is saying. You can just create a bitmap and messure the string. I have this code I use to find the width/length in pixel. Just change the font and size.

// Bitmap class namespace:
using System.Drawing;

...

private float GetWidthOfString(string str)
{
    Bitmap objBitmap = default(Bitmap);
    Graphics objGraphics = default(Graphics);

    objBitmap = new Bitmap(500, 200);
    objGraphics = Graphics.FromImage(objBitmap);

    SizeF stringSize = objGraphics.MeasureString(str, new Font("Arial", 12));

    objBitmap.Dispose();
    objGraphics.Dispose();
    return stringSize.Width;
}

Just wanted to show an example.