12

I'm trying to achieve framed texts (using Windows Forms), e.g.:

enter image description here

Height is always the same, because my strings are less than 20 chars. What about width? Is there any way to get it automatically?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Patryk
  • 3,042
  • 11
  • 41
  • 83
  • possible duplipcate: http://stackoverflow.com/questions/7714022/how-to-get-a-string-width – default Dec 17 '12 at 12:47
  • Possible duplicate of [How can I convert a string length to a pixel unit?](http://stackoverflow.com/questions/451903/how-can-i-convert-a-string-length-to-a-pixel-unit) – Jim Fell May 17 '16 at 17:15

2 Answers2

17

Use Graphics.MeasureString()

From MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx

private void MeasureStringMin(PaintEventArgs e)
{
    // Set up string. 
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
12

If you don't feel like dealing with the Paint eventhandler, you could try the TextRenderer class. It has a static method that is identical to the MeasureString() method in the above answer. In this class it is called MeasureText however.

Masoud
  • 8,020
  • 12
  • 62
  • 123
Yun
  • 121
  • 1
  • 2