Drawing Text on a Form
In this lesson, you will learn how to draw text on a form using graphics methods.
In an earlier lesson, you learned how to display text using a Label control. There are cases, however, when you may want or need to draw the text yourself using graphics methods. For example, if you want text that is slanted, you can't use a Label control—but you can use graphics methods to draw text at any angle.
To draw text on a form or control, you use the DrawString graphics method. Like the other draw methods, DrawString takes a Brush object that determines the color, and coordinates that specify where to draw the text—in this case, the X and Y coordinates of the upper-left corner of the bounding rectangle for the text.
The DrawString method also has two additional arguments—the string that you want to draw, and the font that determines what the text looks like. In order to specify the font, you must first create a Font object, and then use that object as an argument to the DrawString method.
To draw text
On the File menu, choose New Project.
In the New Project dialog box, in the Templates pane, click Windows Application.
In the Name box, type DrawText and then click OK.
A new Windows Forms project opens.
Double-click the form to open the Code Editor, and then select Paint from the Events dropdown list.
In the Form1_Paint event handler, add the following code.
Press F5 to run the program. You should see the text displayed on the form.
Keep the project open—you will be adding to it in the next procedure.
In order to draw text at an angle, you need to use another type of graphics method called a transform. There are several types of transforms available for different graphics effects; in this case, you will use the RotateTransform method.
The RotateTransform method takes a single argument, the angle at which to rotate the text. The transformation is performed on the line of code following the RotateTransform method; you could also use it to rotate shapes or lines drawn using the other draw methods.
To draw rotated text
In the Form1_Paint event handler, add the following code below the code that you entered earlier.
Press F5 to run the program. You should see the rotated text displayed on the form.
In this lesson, you learned how to use the DrawString method to display text. In the next lesson, you will learn to display an image using graphics methods.
Next Lesson: Drawing an Image on a Form