Appunti di Programmazione

Allineare stringhe usando "DrawString"

Inserisco quà il codice per allineare delle stringhe incolonnate, usando il metodo Graphics.DrawString(...).
L'idea di base è quella di misurare l'ampiezza del testo che deve essere rappresentato e poi disegnarlo in modo da essere incolonnato e allineato a destra o sinistra in base alle proprie preferenze.
L''esempio che segue realizza un allineamento a destra.

Public Class Form1

    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

        Allinea(e)

    End Sub

    Private Sub Allinea(ByVal e As PaintEventArgs)

        Dim n1 As Double = 132.91
        Dim n2 As Double = 95.1
        Dim s As String = ""
        Dim myBrush As New SolidBrush(Color.Blue)
        Dim myFont As New Font("Arial", 16)
        Dim myWidth As New SizeF

        s = String.Format("{0:C}", n1)
        myWidth = e.Graphics.MeasureString(s, myFont)
        e.Graphics.DrawString(s, myFont, myBrush, 150 - myWidth.Width, 20)

        s = String.Format("{0:C}", n2)
        myWidth = e.Graphics.MeasureString(s, myFont)
        e.Graphics.DrawString(s, myFont, myBrush, 150 - myWidth.Width, 40)

    End Sub

End Class