VB.NET WinForms: DrawString does not center, despite using Stringformat.Center

62 Views Asked by At

I'm trying to draw my text in the center of my (test) rectangle.

my (simplified) code:

Sub Main()

    Using x As New Form1()
        x.ShowDialog()
    End Using

End Sub

Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Dim g As Drawing.Graphics = Me.CreateGraphics

        Dim rect As New Rectangle(3, 3, 15, 15)
        Dim sf As New StringFormat
        sf.LineAlignment = StringAlignment.Center
        sf.Alignment = StringAlignment.Center

        g.DrawString("0", New Font("Verdana", 6.0!, FontStyle.Regular, GraphicsUnit.Point, 0), New SolidBrush(Color.Black), rect, sf)
        g.DrawRectangle(New Pen(New SolidBrush(Color.HotPink), 1), rect)

    End Sub

End Class

which yields the following result

enter image description here

It looks 'ok', but it's not perfectly centered.

enter image description here

How can I align this perfectly centered?

I have tried different fonts and font sizes, but to no avail.

0

There are 0 best solutions below