Alex Rivera | Logout

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

Asked 2011-04-05T14:58:49.023
11

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.

Edit
Report

2 Answers

15

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.

answered 2012-09-28T08:01:03.803
3

String.Length

Returns the length of the string (number of characters).

C#

string MyString = "Stack Overflow String";
Response.Write(MyString.Length);

VB.net

Dim MyString As String = "Stack Overflow String"
Response.Write(MyString.Length);

MSDN Reference

http://msdn.microsoft.com/en-us/library/system.string.length.aspx

Physical String Size Serverside

I'm not sure why so many people are apparently determined to put forward the idea that it is 'flat out impossible' to do this server side, it isn't. You just need to be a little bit creative, and be willing to do a lot of testing.

There is no native function I know of to measure the pixel dimensions of a string. You can achieve it in the following ways. Note you need to know:

  • The font family
  • Font size
  • Container dimensions (for when the text wraps lines)
  • Any other CSS rules such as word spacing are going to make the calculation a lot less accurate and more complex. Try and avoid it if accuracy is important.

1. Render it to an image and measure image size

Draw the text to a bitmap, and then measure it. This should be reasonably exact.

2. Use a fixed width font

If you are using a fixed width font and the text doesn't wrap, you can simply multiply its width by the number of characters.

3. Rough estimation

You could get a reasonably rough estimation on non fixed width fonts by picking some arbitrary character width number and multiplying it by total characters. Depends how accurate you want to be.

answered 2011-04-05T15:01:04.447

Your Answer