3

I'm drawing text in VB.net by using:

gfx.DrawString(_bText, New Font("Tahoma", 5), Brushes.Black, New Point(25, 5))

where gfx is a graphics object using my control. The x point is correct but I need the y to be the center of the current contol (vertically). Is there an easy way to do this?

Freesnöw
  • 30,619
  • 30
  • 89
  • 138

3 Answers3

3

You need to look at the Graphics.MeasureString method

Using this you can find the Height of your text in the context you give it. You then need to find the Y value to start drawing your text using something like this:

(ControlHeight/2) - (TextHeight/2)
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
2

Use the DrawString overload that takes a StringFormat argument. Set its Alignment property to Center.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

TextRenderer has a VerticalCenter flag:

Dim r As New Rectangle(25, 0, myControl.ClientSize.Width - 25, _
                              myControl.ClientSize.Height)

Using myFont As New Font("Tahoma", 5)
  TextRenderer.DrawText(gfx, _bText, myFont, r, _
                        Color.Black, Color.Empty, _
                        TextFormatFlags.VerticalCenter)
End Using
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • 1
    TextFormatFlags.VerticalCenter and HorizontalCenter can be combinded using an OR. In C# it is like this: TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter – James Aug 01 '12 at 10:00