TextRenderer.MeasureText Method (IDeviceContext, String, Font)
.NET Framework 2.0
Note: This method is new in the .NET Framework version 2.0.
Provides the size, in pixels, of the specified text drawn with the specified font in the specified device context.
Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)
Assembly: System.Windows.Forms (in system.windows.forms.dll)
public static Size MeasureText ( IDeviceContext dc, String text, Font font )
public static function MeasureText ( dc : IDeviceContext, text : String, font : Font ) : Size
Parameters
- dc
The device context in which to measure the text.
- text
The text to measure.
- font
The Font to apply to the measured text.
Return Value
The Size, in pixels, of text drawn in a single line with the specified font in the specified device context.The following code example demonstrates how to use one of the MeasureText methods. To run this example, paste the code into a Windows Form and call DrawALineOfText from the form's Paint event handler, passing e as PaintEventArgs.
private static void DrawALineOfText(PaintEventArgs e) { // Declare strings to render on the form. string[] stringsToPaint = { "Tail", "Spin", " Toys" }; // Declare fonts for rendering the strings. Font[] fonts = { new Font("Arial", 14, FontStyle.Regular), new Font("Arial", 14, FontStyle.Italic), new Font("Arial", 14, FontStyle.Regular) }; Point startPoint = new Point(10, 10); // Set TextFormatFlags to no padding so strings are drawn together. TextFormatFlags flags = TextFormatFlags.NoPadding; // Declare a proposed size with dimensions set to the maximum integer value. Size proposedSize = new Size(int.MaxValue, int.MaxValue); // Measure each string with its font and NoPadding value and // draw it to the form. for (int i = 0; i < stringsToPaint.Length; i++) { Size size = TextRenderer.MeasureText(e.Graphics, stringsToPaint[i], fonts[i], proposedSize, flags); Rectangle rect = new Rectangle(startPoint, size); TextRenderer.DrawText(e.Graphics, stringsToPaint[i], fonts[i], startPoint, Color.Black, flags); startPoint.X += size.Width; } }
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.