Drawing Text


The Graphics object’s DrawString method draws text. It provides several overloaded versions that let you specify the string, font, positioning, and alignment information.

One of the simplest versions of DrawString takes only four parameters: the text to draw, the font to use, the brush to use when filling the text, and the position where the text should start. The following code draws some text starting at the point (10, 10) on the form. It then draws a circle around this point.

  Private Sub Form1_Paint(ByVal sender As Object, _  ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint     Dim txt As String = "The quick brown fox jumps over the lazy dog."     Using big_font As New Font("Times New Roman", 30, FontStyle.Bold)         e.Graphics.TextRenderingHint = _             System.Drawing.Text.TextRenderingHint.AntiAliasGridFit         e.Graphics.DrawString(txt, big_font, Brushes.Black, 10, 10)         e.Graphics.DrawEllipse(Pens.Black, 8, 8, 4, 4)     End Using End Sub  

Figure 22-1 shows the result. Note that the text doesn’t begin exactly at the point (10, 10). The text contains some leading space on the top and bottom that moves it slightly right and downward from the starting point.

image from book
Figure 22-1: Text doesn’t begin exactly at the starting point passed to the DrawString method.

Note also that the text runs blithely off the edge of the form. The following section describes ways you can format text so it automatically provides alignment and wrapping as necessary.

DrawString automatically starts a new line when it encounters a Carriage Return/Line Feed pair in the text. It also advances to the next tab stop when it encounters a Tab character. The following code is similar to the previous version, except that the text includes Tab characters and Carriage Return/Line Feed pairs:

  Private Sub Form1_Paint(ByVal sender As Object, _  ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint     Dim txt As String = "The" & vbTab & "quick" & vbCrLf & _         "brown" & vbTab & "fox" & vbCrLf & _         "jumps" & vbTab & "over" & vbCrLf & _         "the" & vbTab & "lazy" & vbCrLf & _         "dog."     Using big_font As New Font("Times New Roman", 30, FontStyle.Bold)         e.Graphics.TextRenderingHint = _             System.Drawing.Text.TextRenderingHint.AntiAliasGridFit         e.Graphics.DrawString(txt, big_font, Brushes.Black, 10, 10)         e.Graphics.DrawEllipse(Pens.Black, 8, 8, 4, 4)     End Using End Sub 

Figure 22-2 shows the result.

image from book
Figure 22-2: DrawString automatically processes Tab characters and Carriage Return/Line Feed pairs.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net