Recipe 9.17. Drawing Text


You want to draw some nicely formatted text on the drawing surface.


Sample code folder: Chapter 09\DrawingText

The primary tool for drawing text is the Graphics.DrawString() method. To make adjustments to the text, you can alter the font's properties, apply transformations to the canvas itself, or use a StringFormat object. This recipe's sample code uses each of these methods to display a string of text.


Create a new Windows Forms application, and add the following controls to Form1:

  • A TextBox control named DisplayText. Set its Multiline property to true and its ScrollBars property to Vertical. Size it so that you can see multiple lines of user-entered text.

  • A CheckBox control named UseBold. Set its Text property to Bold.

  • A CheckBox control named UseItalic. Set its Text property to Italic.

  • A CheckBox control named UseUnderline. Set its Text property to Underline.

  • A CheckBox control named UseStrikeout. Set its Text property Strikeout.

  • ACheckBox control named ShowBoundingBox. Set its Text property to Show Bounding Box.

  • AComboBox control named DisplayAlign. Set its DropDownStyle property to DropDownList.

  • A trackBar control named DisplayRotate. Set its Minimum property to 0, its Maximum property to 360, its TickFrequency property to 15, its SmallChange property to 15, and its LargeChange property to 60. The trackBar control appears in the All Windows Forms section of the Toolbox by default.

  • A Button control named ActDisplay. Set its Text property to Display.

  • A PictureBox control named DrawingArea. Set its BackColor property to White and its BorderStyle property to Fixed3D.

Add informational labels if desired. The form should look like Figure 9-25.

Figure 9-25. The controls on the text drawing sample

Figure 9-25.

Now add the following source code to the form's class template:

 Private Sub ActDisplay_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles ActDisplay.Click    ' ----- Force the   text to redisplay.    DrawingArea.Invalidate() End Sub Private Sub DrawingArea_Paint(ByVal sender As Object, _       ByVal e As System.Windows.Forms.PaintEventArgs) _       Handles DrawingArea.Paint    ' ----- Refresh the drawing area.    Dim mainFont As Font    Dim   textArea As Rectangle    Dim textStyle As New FontStyle    Dim textFormat As StringFormat    Dim alignParts() As String    ' ----- Clear any existing content.    e.Graphics.Clear(Color.White)    ' ----- Build the font used for the display text.    textStyle = FontStyle.Regular    If (UseBold.Checked = True) Then _       textStyle = textStyle Or FontStyle.Bold    If (UseItalic.Checked = True) Then _       textStyle = textStyle Or FontStyle.Italic    If (UseUnderline.Checked = True) Then _       textStyle = textStyle Or FontStyle.Underline    If (UseStrikeout.Checked = True) Then _       textStyle = textStyle Or FontStyle.Strikeout    mainFont = New Font("Arial", 12, textStyle)    ' ----- Move the (0,0) origin to the center of the    '       display.    e.Graphics.TranslateTransform( _       DrawingArea.ClientRectangle.Width / 2, _       DrawingArea.ClientRectangle.Height / 2)    ' ----- Determine where the main text will go. The Offset    '       method repositions the rectangle's coordinates    '       by the given X and Y values.    textArea = New Rectangle(20, 20, _       DrawingArea.ClientRectangle.Width - 40, _       DrawingArea.ClientRectangle.Height - 40)    textArea.Offset( _       -CInt(DrawingArea.ClientRectangle.Width / 2), _       -CInt(DrawingArea.ClientRectangle.Height / 2))    ' ----- Prepare the alignment.    textFormat = New StringFormat    alignParts = Split(DisplayAlign.Text, ",")    Select Case alignParts(0)       Case "Left"            textFormat.Alignment = StringAlignment.Near       Case "Center"            textFormat.Alignment = StringAlignment.Center       Case "Right"          textFormat.Alignment = StringAlignment.Far    End Select    Select Case alignParts(1)       Case "Top"          textFormat.LineAlignment = StringAlignment.Near       Case "Middle"          textFormat.LineAlignment = StringAlignment.Center       Case "Bottom"          textFormat.LineAlignment = StringAlignment.Far    End Select    ' ----- Rotate the world if requested.    If (DisplayRotate.Value <> 0) Then       e.Graphics.RotateTransform(DisplayRotate.Value)    End If    ' ----- Draw the bounding box if requested.    If (ShowBoundingBox.Checked = True) Then       e.Graphics.DrawRectangle(Pens.Gray, textArea)    End If    ' ----- Draw the main text.    e.Graphics.DrawString(DisplayText.Text, mainFont, _       Brushes.Black, textArea, textFormat)    ' ----- Clean up.    mainFont.Dispose() End Sub Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load    ' ----- Build the list of alignments.    DisplayAlign.Items.Add("Left,Top")    DisplayAlign.Items.Add("Left,Middle")    DisplayAlign.Items.Add("Left,Bottom")    DisplayAlign.Items.Add("Center,Top")    DisplayAlign.Items.Add("Center,Middle")    DisplayAlign.Items.Add("Center,Bottom")    DisplayAlign.Items.Add("Right,Top")    DisplayAlign.Items.Add("Right,Middle")    DisplayAlign.Items.Add("Right,Bottom")    DisplayAlign.SelectedIndex = 0 End Sub 

To use the program, enter some text in the TextBox field, and adjust the other controls as desired to alter the text. Then click the Display button to refresh the displayed text. Figure 9-26 shows some sample text displayed through the program.

Figure 9-26. Rotated and embellished text

The Graphics. DrawString() method is pretty simple to use: you pass it a text string, a position (or bounding rectangle), a font, and a colored or patterned brush, and the text appears on the canvas. Except for how the position and boundaries of the text are specified, there isn't that much flexibility in the method itself. However, there is flexibility in the values passed to the method. Changes to the font or font styles, as demonstrated in this code, clearly have an impact on the results. Similarly, you can create any type of solid, patterned, or image-based brush, and use it to draw the text itself.

Transformations made to the canvas also impact the text output. This recipe's code applies two transformations to the canvas: it repositions the X-Y coordinate system origin from the upper-left corner of the canvas to the center, and it rotates the canvas if requested by the user so that the text appears rotated. Recipe 9.18 discusses the reasons for these two transformations in more detail.

The Drawing.StringFormat class, used in this sample to align the text within its bounding box, provides additional text-drawing options. The StringFormat.FormatFlags property lets you set options that adjust how the text appears in its bounding box. For instance, you can indicate whether the text should automatically wrap or not. The StringFormat.HotkeyPrefix property lets you indicate which character should be used to draw shortcut-key underlines below specific letters of the text, as is done using "&" in Label and other controls.

See Also

Many of the recipes in this chapter show text being formatted and output in a variety of formats and displays.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: