Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDraw text centered at a position in VB .NET
DescriptionThis example shows how to draw text centered at a position in VB .NET.
Keywordstext, center text, font
CategoriesGraphics, Strings, VB.NET
 
The CenterTextAt subroutine creates a StringFormat object. It sets the object's LineAlignment and Alignment properties to Center so the text is aligned horizontally and vertically. It then draws the string at the point where the text should be cnetered. The StringFormat object makes Visual Basic center the text.
 
Private Sub CenterTextAt(ByVal gr As Graphics, ByVal txt As _
    String, ByVal x As Single, ByVal y As Single)
    ' Mark the center for debugging.
    gr.DrawLine(Pens.Red, x - 10, y, x + 10, y)
    gr.DrawLine(Pens.Red, x, y - 10, x, y + 10)

    ' Make a StringFormat object that centers.
    Dim sf As New StringFormat
    sf.LineAlignment = StringAlignment.Center
    sf.Alignment = StringAlignment.Center

    ' Draw the text.
    gr.DrawString(txt, Me.Font, Brushes.Black, x, y, sf)
    sf.Dispose()
End Sub
 
This is a bit easier than the VB 6 version. It's also more flexible because the StringFormat object can align text on the left, right, top, bottom, or center of a point or within a rectangle.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated