Graphics.MeasureString Method (String, Font, Int32)
Measures the specified string when drawn with the specified Font.
Assembly: System.Drawing (in System.Drawing.dll)
String to measure.
Maximum width of the string in pixels.
The width parameter specifies the maximum value of the width component of the returned SizeF structure (Width). If the width parameter is less than the actual width of the string, the returned Width component is truncated to a value representing the maximum number of characters that will fit within the specified width. To accommodate the entire string, the returned Height component is adjusted to a value that allows displaying the string with character wrap.
The MeasureString method is designed for use with individual strings and includes a small amount of extra space before and after the string to allow for overhanging glyphs. Also, the DrawString method adjusts glyph points to optimize display quality and might display a string narrower than reported by MeasureString. To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
Creates a string to measure and a font object set to Arial (16 point).
Sets the maximum width of the string.
Creates a size object and uses it, the font object, and the maximum string width to measure the size of the string.
Draws a red rectangle using the measured size of the string.
Draws the string within the drawn rectangle.
Available since 1.1