Draw Text with GDI+ and Visual Basic 2003 (Visual Basic.NET)

This article and source code demonstrate how to draw text with Visual Basic and the Microsoft.NET System.Drawing.Drawing2D and System.Drawing.Drawing2D namespaces.

A Visual Studio 2003 Windows Forms application created with Visual Basic implements .NET drawing classes to draw text and apply the following effects: brush, shadow, emboss, block, engrave, shear, reflect, and wrap.

A snapshot of the application is shown below.

Sample of Code From the  Application

 

The code below draws text with a ‘block’ effect’. Download the source code to get code to draw text with additional effects.

 

‘ To create a block text effect, draw the text twice, first offset in one color, then with a second color.

Private Sub BlockTextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BlockTextButton.Click

    Dim textSize As SizeF

    Dim g As Graphics

    Dim theBackBrush As Brush = Brushes.Black

    Dim theForeBrush As Brush = Brushes.Aquamarine

    Dim theFont As New Font(“Times New Roman”, Me.FontSizeUpDown.Value, FontStyle.Regular)

    Dim xLocation, yLocation As Single ‘ Used for the location

    Dim i As Integer

 

    ‘ Create a Graphics object from the picture box & clear it.

    g = DemoPictureBox.CreateGraphics()

    g.Clear(Me.SampleBackColorPictureBox.BackColor)

 

    ‘ Measure the string that is to be drawn.

    textSize = g.MeasureString(Me.TextSampleTextBox.Text, theFont)

 

    ‘ Get the locations once to eliminate redundant calculations

    xLocation = (DemoPictureBox.Width – textSize.Width) / 2

    yLocation = (DemoPictureBox.Height – textSize.Height) / 2

 

    ‘ Draw the Black background first

    ‘   The text must be drawn repeatedly from the offset right to

    ‘   where the main text will be drawn.

    For i = CInt(BlockDepthNumericUpDown.Value) To 0 Step -1

        g.DrawString(TextSampleTextBox.Text, theFont, theBackBrush, _

                xLocation – i, yLocation + i)

    Next

 

    ‘ Draw the second color main text over the first color.

    g.DrawString(TextSampleTextBox.Text, theFont, theForeBrush, xLocation, yLocation)

End Sub

~ bởi duriangroup on Tháng Sáu 1, 2007.

 
%d bloggers like this: