Freesnöw
Freesnöw

Reputation: 32143

Center drawn text

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?

Upvotes: 3

Views: 3436

Answers (3)

LarsTech
LarsTech

Reputation: 81610

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

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941357

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

Upvotes: 2

Matt Wilko
Matt Wilko

Reputation: 27322

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)

Upvotes: 3

Related Questions