AshOoO
AshOoO

Reputation: 1148

How to get a string width

I need to build a function in a class library that take a string and a specific font for this string then get the width of the string

So how could I get the string boundary width ?

Upvotes: 13

Views: 30482

Answers (3)

Behrooz Moghaddam
Behrooz Moghaddam

Reputation: 115

You can use this:

private float getTextSize(string text)
    {
        Font font = new Font("Courier New", 10.0F);
        Image fakeImage = new Bitmap(1, 1);
        Graphics graphics = Graphics.FromImage(fakeImage);
        SizeF size = graphics.MeasureString(text, font);
        return size.Width;
    }

Upvotes: 3

Josh Darnell
Josh Darnell

Reputation: 11433

Another way to do this is with a TextRenderer, and call its MeasureString method, passing the string and the font type.

MSDN Example:

private void MeasureText1(PaintEventArgs e)
{
    String text1 = "Measure this text";
    Font arialBold = new Font("Arial", 12.0F);
    Size textSize = TextRenderer.MeasureText(text1, arialBold);
    TextRenderer.DrawText(e.Graphics, text1, arialBold, 
        new Rectangle(new Point(10, 10), textSize), Color.Red);  
}

NOTE: This is just an alternate solution to the (equally valid) one already posted by @Neil Barnwell (in case you already have a reference to System.Windows.Forms in your project, this might be more convenient).

Upvotes: 18

Neil Barnwell
Neil Barnwell

Reputation: 42125

You can get a Graphics object (using Control.CreateGraphics() on the container you intend the text for) and call MeasureString() to do this. It's a fairly common GDI+ technique.

More information from MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

Upvotes: 13

Related Questions