What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitlePrecisely determine the size of text drawn by a Graphics object in Visual Basic .NET
DescriptionThis example shows how to precisely determine the size of text drawn by a Graphics object in Visual Basic .NET.
KeywordsGraphics, DrawString, GraphicsPath, draw text, draw string, text, text size, VB.NET
CategoriesVB.NET, Graphics
Thanks to Manfred for his help on this.

The Graphics object's MeasureString method tells you how big a piece of text will be when drawn but it is not very precise and leaves extra room around the text. You can get a more accurate measurement by considering font metrics but even that includes some extra space. This method allows you to measure drawn text much more precisely.

The example program's Paint event handler uses the following code to draw some text surrounded by a tightly enclosing rectangle. First it creates the font that it will use to draw the text. It builds StringFormat and PointF objects to determine how and where the text will be positioned.

Next the code makes a GraphicsPath object and adds the text to it, using the same font characteristics it used to build the font, and it draws the GraphicsPath. Then it uses the GraphicsPath's GetBounds method to ghet the text's bounds and it draws the bounding rectangle. The result fits the text very closely.

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _
    System.Windows.Forms.PaintEventArgs) Handles _
    ' Make the font. Use Pixels as the unit.
    Const FONT_SIZE As Integer = 100
    Dim the_font As New Font("Times New Roman", FONT_SIZE, _
        FontStyle.Bold, GraphicsUnit.Pixel)

    ' Make the text origin and StringFormat.
    Dim sf As New StringFormat
    sf.Alignment = StringAlignment.Center
    sf.LineAlignment = StringAlignment.Center
    Dim origin As New PointF(Me.ClientSize.Width / 2, _
        Me.ClientSize.Height / 2)

    ' Add the text to the GraphicsPath.
    Dim text_path As New GraphicsPath
    text_path.AddString("Message", _
        the_font.FontFamily, CInt(FontStyle.Bold), _
        FONT_SIZE, origin, sf)

    ' Draw the text.
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias
    e.Graphics.FillPath(Brushes.Blue, text_path)
    e.Graphics.DrawPath(Pens.Blue, text_path)

    ' Draw the bounding rectangle.
    Dim text_rectf As RectangleF = text_path.GetBounds()
    Dim text_rect As Rectangle = Rectangle.Round(text_rectf)
    e.Graphics.DrawRectangle(Pens.Red, text_rect)

    ' Cleanup.
End Sub
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.