Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top