Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Drawing Text

Printing text on a Graphics object is very similar to drawing a shape, and the method name even contains the word Draw, in contrast to Print. To draw text on a Graphics object, call the DrawString() method. The basic format for DrawString() looks like this:

object.DrawString(stringoftext, font, brush, topX, leftY);

A few of these items are probably new to you. The argument stringoftext is fairly self-explanatory; it's the string you want to draw on the Graphics object. The topX and leftY arguments represent the coordinate at which drawing will take place; they represent the upper-left corner of the string, as illustrated in Figure 4.

Figure 4 The coordinate specified in DrawString() represents the upper-left corner of the printed text.

The arguments brush and font aren't so obvious. Both arguments accept objects. A brush is similar to a pen. However, whereas a pen describes the characteristics of a line, a brush describes the characteristics of a fill. For example, both pens and brushes have a color, but where pens have an attribute for defining a line style, such as dashed or solid, a brush has an attribute for a fill pattern, such as solid, hatched, weave, or trellis. When drawing text, a solid brush is usually sufficient. You can create brushes in much the same way as you create pens, or you can use one of the standard brushes available from the System.Drawing.Brushes class.

A Font object defines characteristics used to format text, including the character set (Times New Roman, Courier, for example), size (point size), and style (bold, italic, normal, underlined, and so on). To create a new Font object, you could use code such as the following:

Font objFont;
objFont = new System.Drawing.Font("Arial", 30);

The text Arial in this code is the name of a font installed on my computer. In fact, Arial is one of the few fonts installed on all Windows computers. If you supply the name of a font that doesn't exist, C# will use a default font. The second parameter is the point size of the text. If you want to use a style other than normal, you can provide a style value as a third parameter, like this:

objFont = new System.Drawing.Font("Arial Black", 30,FontStyle.Bold);


objFont = new System.Drawing.Font("Arial Black", 30,FontStyle.Italic);

In addition to creating a Font object, you can also use the font of an existing object, such as a Form. For example, the following statement prints text to a Graphics object using the font of the current form:

objGraphics.DrawString("This is the text that prints!", 
            this.Font,System.Drawing.Brushes.Azure, 0, 0);
  • + Share This
  • 🔖 Save To Your Account