Drawing Text
This section briefly discusses the drawing of text.
The
DrawString method draws a text string on a graphics surface. It has
many overloaded forms. Drawstring takes arguments that identify the
text, font, brush, starting location, and string format.
Listing 3.6 uses the DrawString method to draw "Hello GDI+ World!" on a form.
LISTING 3.6: Drawing text
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint e.Graphics.DrawString("Hello GDI+ World!", New Font("Verdana", 16), New SolidBrush(Color.Red), New Point(20, 20)) End Sub
Note: You
might notice in Listing 3.6 that we create Font, SolidBrush, and Point
objects directly as parameters of the DrawString method. This method of
creating objects means that we can't dispose of these objects, so some
cleanup is left for the garbage collector.
Figure 3.7 shows the output from Listing 3.6
FIGURE 3.7: Drawing text
Now
let's see another example of drawing text- this time using the
StringFormat class, which defines the text format. Using StringFormat,
you can set flags, alignment, trimming, and other options for the text.
Listing 3.7 shows different ways to draw text on a graphics surface. In
this example the FormatFlags property is set to
StringFormatFlags.DirectionVertical, which draws a vertical text.
LISTING 3.7: Using DrawString to draw text on a graphics surface
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint ' create brushes Dim blueBrush As New SolidBrush(Color.Blue) Dim redBrush As New SolidBrush(Color.Red) Dim greenBrush As New SolidBrush(Color.Green) ' Create a rectangle Dim rect As New Rectangle(20, 20, 200, 100)
' The text to be drawn Dim DrawString As [String] = "Hello GDI+ World!"
' Create a Font object Dim DrawFont As New Font("Verdana", 14) Dim x As Single = 100.0F Dim y As Single = 100.0F Dim DrawFormat As New StringFormat()
' Set string format flag to direction vertical, ' which draws text vertically DrawFormat.FormatFlags = StringFormatFlags.DirectionVertical
' Draw string e.Graphics.DrawString("Drawing text", New Font("Tahoma", 14), greenBrush, rect) e.Graphics.DrawString(DrawString, New Font("Arial", 12), redBrush, 120, 140) e.Graphics.DrawString(DrawString, DrawFont, blueBrush, x, y, DrawFormat)
' Dispose of objects blueBrush.Dispose() redBrush.Dispose() greenBrush.Dispose() DrawFont.Dispose() End Sub
Figure 3.8 shows the output from Listing 3.7
FIGURE 3.8: Drawing text with different directions
Conclusion
Hope the article would have helped you in understanding drawing Text in GDI+. Read other articles on GDI+ on the website.
|
請先 登入 以發表留言。