.NET Framework Class Library
TextRenderer.MeasureText Method (String, Font)
Provides the size, in pixels, of the specified text when drawn with the specified font.
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
Syntax
Visual Basic
Public Shared Function MeasureText ( _ text As String, _ font As Font _ ) As Size
C#
public static Size MeasureText( string text, Font font )
Visual C++
public: static Size MeasureText( String^ text, Font^ font )
F#
static member MeasureText : text:string * font:Font -> Size
Parameters
- text
- Type: System.String
The text to measure.
- font
- Type: System.Drawing.Font
The Font to apply to the measured text.
Return Value
Type: System.Drawing.SizeThe Size, in pixels, of text drawn on a single line with the specified font. You can manipulate how the text is drawn by using one of the DrawText overloads that takes a TextFormatFlags parameter. For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces you should use the versions of DrawText and MeasureText that take a Size and TextFormatFlags parameter. For an example, see MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags).
Remarks
The MeasureText method requires that the text is drawn on a single line.
Examples
The following code example demonstrates how to use the MeasureText method. To run this example, paste the code into a Windows Form and call MeasureText1 from the form's Paint event handler, passing e as PaintEventArgs.
Visual Basic
Private Sub MeasureText1(ByVal e As PaintEventArgs)
Dim text1 As String = "Measure this text"
Dim arialBold As New Font("Arial", 12.0F)
Dim textSize As Size = TextRenderer.MeasureText(text1, arialBold)
TextRenderer.DrawText(e.Graphics, text1, arialBold, _
New Rectangle(New Point(10, 10), textSize), Color.Red)
End Sub
C#
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); }
Version Information
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0.NET Framework Client Profile
Supported in: 4, 3.5 SP1Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
See Also