how to draw GDI multiline text in vb.net

The following example shows that how to draw mulltiline text in vb.net

 Private Sub DrawMultiLine()
        Dim textSize As SizeF
        Dim g As Graphics
        Dim myForeBrush As Brush = Brushes.Black
        Dim fontconverter As New FontConverter
        Dim myFont As Font
        myFont = fontconverter.ConvertFromString(txtFont.Text)
 
        ' Create a Graphics object from the picture box & clear it.
        g = PictureBox1.CreateGraphics()
        g.Clear(Color.White)
 
        ' Find the Size required to draw the Sample Text.
        textSize = g.MeasureString(txtText.Text, myFont)
 
        ' Draw the main text.
        g.DrawString(txtText.Text, myFont, myForeBrush, _
            New RectangleF(0, 0, PictureBox1.Width, PictureBox1.Height))
    End Sub

The above example requires a textbox and picturebox controls on the form. Code creates the objects of the Fontconverter and Font classes. We initialize the graphics object from the CreateGraphics() method and in the last we are using the Graphics.DrawString() method to draw the text of the textbox control on the picturebox.

  • xx

    Whet the use of textSize variable ?

    • textSize is the object of the SizeF class that represents the ordered pair of the width and height (typically width and height of the rectangle).

      So you can also use the last line as :

      g.DrawString(txtText.Text, myFont, myForeBrush, _

      New RectangleF(0, 0, textSize))