RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Master .NET's Text Tricks : Page 4

Learn how to use the Graphics object's methods to draw text in different fonts—clipped, wrapped, aligned, stretched, and rotated in all sorts of ways.

Transforming Text
DrawString draws text using a normal, unmangled font. It won't stretch, rotate, or otherwise contort the font. The Graphics object that provides the DrawString method, however, also provides methods for rotating, translating, and scaling whatever it draws—including text. The Graphics object's TranslateTransform, ScaleTransform, and RotateTransform methods move, stretch, and rotate the drawing.

Figure 7. Transforming Text: The Graphics object can transform text, stretching it horizontally and/or vertically, and translating it to a different location.
For example, the following code draws text that has been stretched vertically. It starts by finding the form's center (cx, cy). It then uses the ScaleTransform method to scale the drawing horizontally by a factor of one (leaving the horizontal size unchanged) and vertically by a factor of six.

Finally, it adds a translation of distance cx in the horizontal direction and cy in the vertical direction. That moves the drawn objects around the point of origin so they are centered in the form. Notice that the final parameter to TranslateTransform is Drawing2D.MatrixOrder.Append. That makes the Graphics object apply the translation after it applies the scaling. By default (for some odd reason), these routines perform their transformations before any previous transformations and it's important to perform them in the proper order. In general, transformations applied in reverse sequence do not produce the same result.

After setting up the Graphics object's transformation, the code draws some text centered at the origin. The transformation stretches it and moves it to the center of the form. Figure 7 shows the result.

   Dim cx As Integer = Me.ClientSize.Width \ 2
   Dim cy As Integer = Me.ClientSize.Height \ 2
   e.Graphics.ScaleTransform(1, 6, Drawing2D.MatrixOrder.Append)
   e.Graphics.TranslateTransform(cx, cy, _
   Using string_format As New StringFormat()
      string_format.Alignment = StringAlignment.Center
      string_format.LineAlignment = StringAlignment.Center
      e.Graphics.DrawString("StretchedText", Me.Font, _
           Brushes.Blue, 0, 0, string_format)
   End Using
The Graphics object's RotateTransform method rotates anything you draw around the origin. Often it is more convenient to rotate around a point other than the origin. While RotateTransform won't do that for you, it's easy enough to build a rotation around some other point by first translating that point to the origin, performing the rotation, and then translating the point back to its original location.

The RotateAt method shown in the following code makes this process easy. It prepares a Graphics object to rotate around an arbitrary point.

Figure 8. Rotating Text: This output shows month names drawn using the RotateAt method, which rotates text around an arbitrary point.
   ' Prepare the Graphics object to rotate 
   ' at the indicated point.
   Private Sub RotateAt( _
      ByVal gr As Graphics, _
      ByVal cx As Integer, _
      ByVal cy As Integer, _
      ByVal angle As Single)
      gr.TranslateTransform(-cx, -cy, _
      gr.RotateTransform(angle, _
      gr.TranslateTransform(cx, cy, _
   End Sub
The example program RotatedText, shown in Figure 8, uses the RotateAt method to draw rotated month names above a grid.

Shading Text
The Graphics object provides two main groups of graphical routines: those that fill shapes and those that draw them. For example, DrawRectangle outlines a rectangle while FillRectangle fills one. The drawing routines take Pen objects as parameters to control how to draw the lines. Similarly, you pass Brushes to the filling routines to control how to fill areas.

Even though the DrawString method begins with the word "Draw," it actually fills the text with a brush. So far, the examples you've seen have used solid brushes but there's no reason you can't use more exotic brush classes such as TextureBrush, HatchBrush, and LinearGradientBrush.

For example, the following code draws text shaded with a LinearGradientBrush. It finds the center of the form and sets up a StringFormat object to center text over its reference point. It then uses the Graphics object's MeasureString function to find out how big the text will be when it is drawn by the Graphics object using the form's font. The code uses this size to find the corners of the rectangle that will hold the text. It makes a brush to fill the rectangle with a vertical gradient and draws the text with the brush. Finally the code draws the rectangle.

   ' Find the center of the form.
   Dim origin As New PointF( _
      Me.ClientSize.Width \ 2, _
      Me.ClientSize.Height \ 2)
   Const TXT As String = "ShadedText"
   Using string_format As New StringFormat()
      ' See how big the text will be using the form's font.
      string_format.Alignment = StringAlignment.Center
      string_format.LineAlignment = StringAlignment.Center
      Dim txt_size As SizeF = e.Graphics.MeasureString( _
         TXT, Me.Font, origin, string_format)
      ' Make a brush that shades vertically.
      Dim rect As New Rectangle( _
         origin.X - txt_size.Width \ 2, _
         origin.Y - txt_size.Height \ 2, _
         txt_size.Width, _
      Using br As New LinearGradientBrush( _
         rect, Color.Red, Color.Blue, _
         e.Graphics.DrawString(TXT, Me.Font, br, _
            origin, string_format)
Figure 9. Filling Text: You can fill text with any brush, including a LinearGradientBrush, as shown in this figure.
End Using ' br e.Graphics.DrawRectangle(Pens.Red, rect) End Using ' string_format
Figure 9 shows the result. Notice that the rectangle surrounding the text contains some extra space around the edges.

Visual Studio .NET gives you a complete set of powerful tools for drawing text. You can draw text with different fonts at different locations, control clipping, wrapping, and alignment, transform text by stretching or rotating it, and shade and fill it using interesting brushes. Drawing cleverly shaded text that's rotated, stretched, and positioned in exactly the right location can be a bit of work, but with a little practice, your applications will be able to perform text tricks on command.

Rod Stephens is a consultant and author who has written more than a dozen books and two hundred magazine articles, mostly about Visual Basic. During his career he has worked on an eclectic assortment of applications for repair dispatch, fuel tax tracking, professional football training, wastewater treatment, geographic mapping, and ticket sales. His VB Helper web site receives more than 7 million hits per month and provides three newsletters and thousands of tips, tricks, and examples for Visual Basic programmers.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date