Search code examples
vb.netcenterdrawstring

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?


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