0

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.

3
  • Text renderers fit glyphs to the pixel grid for optimum readability. Being off by 1 pixel some times when the left-over white space is not divisible by 2 is thus inevitable. A fixed-pitch font will be more predictable since the glyphs have a fixed width. Commented Nov 17, 2021 at 15:58
  • I've tried Courier and other monospaced fonts, but the result is the same. More often than not, the text is off by more than one pixel. No matter if the rectangle is 15 or 16 pixels in size. Commented Nov 17, 2021 at 17:56
  • If it's just a number between 0 and 9 you can adjust the x and y position of the string. In your g.DrawString(...) just replace the "rect" by the x and y directly. So where you have ...New SolidBrush(Color.Black), rect, sf), you can have it like: New SolidBrush(Color.Black), 6,6, sf) Commented Nov 17, 2021 at 22:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.