Graphics.MeasureString Method (String, Font, PointF, StringFormat)
Assembly: System.Drawing (in System.Drawing.dll)
'Declaration Public Function MeasureString ( _ text As String, _ font As Font, _ origin As PointF, _ stringFormat As StringFormat _ ) As SizeF
- Type: System.String
String to measure.
- Type: System.Drawing.PointF
PointF structure that represents the upper-left corner of the string.
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)
Creates a point to locate the upper-left corner of the string.
Creates a string format object and sets its format flags to DirectionVertical.
Creates a size object to measure the string.
Measures the size of the string, using the string, the font object, the locating point, and the string format.
Draws a red rectangle using the locating point and the measured size of the string.
Draws the string within the drawn rectangle.
The result is a vertical rectangle enclosing a vertical string.
Private Sub MeasureStringPointFFormat(ByVal e As PaintEventArgs) ' Set up string. Dim measureString As String = "Measure String" Dim stringFont As New Font("Arial", 16) ' Set point for upper-left corner of string. Dim x As Single = 50.0F Dim y As Single = 50.0F Dim ulCorner As New PointF(x, y) ' Set string format. Dim newStringFormat As New StringFormat newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical ' Measure string. Dim stringSize As New SizeF stringSize = e.Graphics.MeasureString(measureString, stringFont, _ ulCorner, newStringFormat) ' Draw rectangle representing size of string. e.Graphics.DrawRectangle(New Pen(Color.Red, 1), x, y, _ stringSize.Width, stringSize.Height) ' Draw string to screen. e.Graphics.DrawString(measureString, stringFont, Brushes.Black, _ ulCorner, newStringFormat) End Sub