- Basic Text Display
- Windows Fonts
- Font Class
- Displaying Text
- Other Format Settings
Other Format Settings
You can apply a variety of other format settings to text output using the StringFormat class, which is passed as an argument to the DrawString() method. The most useful is control of text alignment, both vertically and horizontally. You control these by setting the Alignment and LineAlignment properties for vertical and horizontal alignment, respectively. This is relevant only when you specify text position as a rectangle. The permitted settings, members of the StringAlignment enumeration, are described in Table 2.
Table 2. StringAlignment Members, Alignment Properties, LineAlignment Properties
StringAlignment Member |
Alignment Property |
LineAlignment Property |
Center |
Each line is centered horizontally |
Lines of text are centered vertically |
Far |
Text is right-aligned (for left-to-right languages such as English) |
Text is displayed as close as possible to the bottom of the bounding rectangle. |
Near |
Text is left-aligned (for left-to-right languages such as English) |
Text is displayed as close as possible to the top of the bounding rectangle. |
The final text display trick is how to display vertical text, which is done by using the StringFormat object. You must set its FormatFlags property as shown in this code snippet (the output is shown in Figure 5):
StringFormat sf = new StringFormat(); sf.FormatFlags = StringFormatFlags.DirectionVertical; g.DrawString(msg, f, br, r, sf);
Figure 5 Displaying vertically oriented text with the FormatFlags property
Note, however, that the order of lines is not what you probably want, with the first line on the left. To reverse it, you must also specify a right-to-left text direction flag, as shown in this code:
StringFormat sf = new StringFormat(); sf.FormatFlags = StringFormatFlags.DirectionVertical | StringFormatFlags.DirectionRightToLeft; g.DrawString(msg, f, br, r, sf);
The output, shown in Figure 6, has the first line on the right as desired.
Figure 6 Displaying vertically oriented text with the first line on the right
What if you want to display text at other orientations, such as bottom to top or angled? It requires the use of a geometrical transformation, which is beyond the scope of this article. I’ll be dealing with transformations in a future article, so stay tuned.