Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a string width

Tags:

string

c#

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 ?

like image 645
AshOoO Avatar asked Oct 10 '11 14:10

AshOoO


1 Answers

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).

like image 157
Josh Darnell Avatar answered Nov 02 '22 22:11

Josh Darnell