As we discussed in Chapter 3, the DrawString method of the Graphics class can be used to draw text on a graphics surface. The DrawString method takes a string, font, brush, and starting point.
Listing 5.8 creates three different fonts and draws text on a form using the DrawString method. Each DrawString method uses a different color and font to draw the string.
Listing 5.8 Drawing text on a graphics surface
private void DrawText_Click(object sender, System.EventArgs e) { // Create a Graphics object Graphics g = this.CreateGraphics(); // Create font families FontFamily verdanaFamily = new FontFamily("Verdana"); FontFamily arialFamily = new FontFamily("Arial"); // Construct Font objects Font verdanaFont = new Font( "Verdana", 10); Font arialFont = new Font( arialFamily, 16, FontStyle.Bold); Font tahomaFont = new Font( "Tahoma", 24, FontStyle.Underline|FontStyle.Italic); // Create Brush and other objects PointF pointF = new PointF(30, 10); SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255)); // Draw text using DrawString g.DrawString("Drawing Text", verdanaFont, new SolidBrush(Color.Red), new PointF(20,20) ); g.DrawString("Drawing Text", arialFont, new SolidBrush(Color.Blue), new PointF(20, 50) ); g.DrawString("Drawing Text", tahomaFont, new SolidBrush(Color.Green), new PointF(20, 80) ); // Dispose of objects solidBrush.Dispose(); g.Dispose(); }
Figure 5.13 shows the output from Listing 5.8. The first text is 10-point Verdana; the second, 14-point Arial Bold; and the third, 24-point Tahoma Italic.
Figure 5.13. Fonts with different styles and sizes
Note
See Chapter 3 (Section 3.2.1.5) for more overloaded forms of the DrawString method.
5.4.1 Drawing Formatted Text
The DrawString method can also be used to draw formatted text. To format text, the .NET Framework library provides the StringFormat class, which can be passed as a parameter of the DrawString methods. The StringFormat class provides members to set alignment, line spacing, digit substitution, trimming, and tab stops. These classes are defined in the System.Drawing namespace.
5.4.1.1 Alignment and Trimming
The Alignment and Trimming properties of the StringFormat class are used to set and get alignment and trimming of text. The Alignment property takes a value of type StringAlignment enumeration, and the Trimming property takes a value of type StringTrimming enumeration.
The LineAlignment property represents the line alignment of text, which also takes a value of type StringAlignment enumeration.
The StringAlignment enumeration specifies the alignment of a text string. Table 5.9 describes the members of the StringAlignment enumeration.
The StringTrimming enumeration specifies how to trim characters from a string that does not completely fit into a layout shape. Table 5.10 describes the members of the StringTrimming enumeration.
Listing 5.9 uses Alignment and Trimming properties to align and trim text strings and draws the text to a form. We use two StringFormat objects: strFormat1 and strFormat2. For strFormat1, we set the alignment to Center, line alignment to Center, and trimming to EllipsisCharacter. For strFormat2, we set the alignment to Far, string alignment to Near, and trimming to Character. Then we use strFormat1 and strFormat2 as parameters of the DrawString method to apply a string format to the text.
Member |
Description |
---|---|
Center |
Text is aligned in the center of a rectangle. |
Far |
Text is aligned as far as possible from the origin position of a rectangle. |
Near |
Text is aligned as close as possible to the origin position of a rectangle. |
Member |
Description |
---|---|
Character |
Text is trimmed to the nearest character. |
EllipsisCharacter |
Text is trimmed to the nearest character, and an ellipsis is inserted at the end of a trimmed line. |
EllipsisPath |
The center is removed from trimmed lines and replaced by an ellipsis. |
EllipsisWord |
Text is trimmed to the nearest word, and an ellipsis is inserted at the end of a trimmed line. |
None |
No trimming. |
Word |
Text is trimmed to the nearest word. |
Listing 5.9 Using the Trimming and Alignment properties of StringFormat
private void menuItem11_Click(object sender, System.EventArgs e) { // Create a Graphics object Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); string text = "Testing GDI+ Text and Font" + " functionality for alignment and trimming."; // Create font families FontFamily arialFamily = new FontFamily("Arial"); // Construct Font objects Font verdanaFont = new Font( "Verdana", 10, FontStyle.Bold); Font arialFont = new Font( arialFamily, 16); // Create rectangles Rectangle rect1 = new Rectangle(10, 10, 100, 150); Rectangle rect2 = new Rectangle(10, 165, 150, 100); // Construct string format and alignment StringFormat strFormat1 = new StringFormat(); StringFormat strFormat2 = new StringFormat(); // Set alignment, line alignment, and trimming // properties of string format strFormat1.Alignment = StringAlignment.Center; strFormat1.LineAlignment = StringAlignment.Center; strFormat1.Trimming = StringTrimming.EllipsisCharacter; strFormat2.Alignment = StringAlignment.Far; strFormat2.LineAlignment = StringAlignment.Near; strFormat2.Trimming = StringTrimming.Character; // Draw GDI+ objects g.FillEllipse(new SolidBrush(Color.Blue), rect1); g.DrawRectangle( new Pen(Color.Black), rect2); g.DrawString(text, verdanaFont, new SolidBrush(Color.White) , rect1, strFormat1); g.DrawString(text, arialFont, new SolidBrush(Color.Red), rect2, strFormat2); // Dispose of objects arialFont.Dispose(); arialFont.Dispose(); verdanaFont.Dispose(); arialFamily.Dispose(); g.Dispose(); }
Figure 5.14 shows the output from Listing 5.9. Text inside the rectangle is trimmed to fit.
Figure 5.14. Alignment and trimming options
5.4.2 Using Tab Stops
Along with the properties discussed in the preceding section, the StringFormat class provides some methods. The GetTabStops and SetTabStops methods can be used to get and set tab stops, respectively. Each of these methods takes two arguments: firstTabOffset and tabStops. The first parameter, firstTabOffset, is a float value that represents the number of spaces between the beginning of a line of text and the first tab stop. The second parameter, tabStops, is an array of float values that represents the number of spaces between tabs.
An application can use the SetTabStops method to generate tabular output on a graphics surface. For example, Listing 5.10 uses SetTabStops to generate a tabular data report. In this example we create a StringFormat object and set its tab stops using the SetTabStops method, and then we call the DrawString method.
In Listing 5.10 we create a table that lists the grades of a student in tabular format. The table has four columns: ID, Math, Physics, and Chemistry. These columns list the grades obtained by a student. As the listing shows, we create a StringFormat object and set the tab stops using the SetTabStops method.
Listing 5.10 Using tab stops to draw tabular data on a graphics surface
private void menuItem12_Click(object sender, System.EventArgs e) { // Create a Graphics object Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Some text data string text = "ID Math Physics Chemistry "; text = text + "- - - - "; text = text + "1002 76 89 92 "; text = text + "1003 53 98 90 "; text = text + "1008 99 78 65 "; // Create a font Font verdanaFont = new Font( "Verdana", 10, FontStyle.Bold); Font tahomaFont = new Font( "Tahoma", 16); // Create brushes SolidBrush blackBrush = new SolidBrush(Color.Black); SolidBrush redBrush = new SolidBrush(Color.Red); // Create a rectangle Rectangle rect = new Rectangle(10, 50, 350, 250); // Create a StringFormat object StringFormat strFormat = new StringFormat(); // Set tab stops of string format strFormat.SetTabStops(5, new float[] {80, 100, 80, 80}); // Draw string g.DrawString("Student Grades Table", tahomaFont, blackBrush, new Rectangle (10, 10, 300, 100)); g.DrawString("=============", tahomaFont, blackBrush, new Rectangle(10, 23, 300, 100)); // Draw string with tab stops g.DrawString(text, verdanaFont, redBrush, rect, strFormat); // Dispose of GDI+ objects tahomaFont.Dispose(); redBrush.Dispose(); blackBrush.Dispose(); g.Dispose(); }
Figure 5.15 shows the output from Listing 5.10. It's easy to present text data in a tabular form by simply using the StringFormat class and its properties.
Figure 5.15. Drawing tabbed text on a form
5.4.3 The FormatFlags Property
The FormatFlags property is useful when an application needs to draw text strings in different layoutssuch as drawing vertical text. FormatFlags takes a value of the StringFormatFlags enumeration. Table 5.11 describes the members of the StringFormatFlags enumeration.
Note
An application can apply more than one StringFormatFlags member by using bitwise combinations.
As Listing 5.11 shows, our sample code draws two strings. One string is drawn from right to left, and the other is vertical. Using FormatFlags is pretty simple. An application creates a StringFormat object, sets its FormatFlags property, and then uses the StringFormat object in the DrawString method. Note that an application can use more than one instance of FormatFlags for the same StringFormat object.
Member |
Description |
---|---|
DirectionRightToLeft |
Draws text right to left in a given rectangle using the DrawString method. |
DirectionVertical |
Draws vertical text in a given rectangle using the DrawString method. The default alignment is left (use the Alignment property to change the text alignment). |
DisplayFormatControl |
Causes control characters such as the paragraph mark to be shown in the output with a representative glyph (e.g., ¶). |
FitBlackBox |
Specifies that no part of any glyph will overhang the bounding rectangle. |
LineLimit |
Specifies that only complete lines will be laid out in the formatting rectangle. |
MeasureTrailingSpaces |
By default, the boundary rectangle returned by the MeasureString method excludes any space at the end of each line. Set this flag to include that space in the measurement. |
NoClip |
By default, clipping is on, which means that any text outside of the formatting rectangle is not displayed. NoClip disables clipping. |
NoFontFallback |
By default, if the specified font is not found, an alternative font will be used. NoFontFallback disables that option and displays an open square for the missing character(s). |
NoWrap |
By default, wrapping is on. NoWrap disables wrapping. |
Listing 5.11 Using FormatFlags to format string text
private void menuItem16_Click(object sender, System.EventArgs e) { // Create a Graphics object Graphics g = this.CreateGraphics(); // Create a rectangle Rectangle rect = new Rectangle(50, 50, 350, 250); // Create two StringFormat objects StringFormat strFormat1 = new StringFormat(); StringFormat strFormat2 = new StringFormat(); // Set format flags of StringFormat objects // with direction right to left strFormat1.FormatFlags = StringFormatFlags.DirectionRightToLeft; // Set direction vertical strFormat2.FormatFlags = StringFormatFlags.DirectionVertical; // Set alignment strFormat2.Alignment = StringAlignment.Far; // Draw rectangle g.DrawRectangle(new Pen(Color.Blue), rect); string str = "Horizontal Text: This is horizontal " + "text inside a rectangle"; // Draw strings g.DrawString(str, new Font("Verdana", 10, FontStyle.Bold), new SolidBrush(Color.Green), rect, strFormat1); g.DrawString("Vertical: Text String", new Font("Arial", 14), new SolidBrush(Color.Red), rect, strFormat2); // Dispose of GDI+ objects g.Dispose(); }
Figure 5.16 shows the output from Listing 5.11. One text string is drawn from right to left (aligned right) in the drawing rectangle, and the other text string is drawn vertically on the left-hand side. An application can even use Alignment, Trimming, and other properties to align and trim text.
Figure 5.16. Using FormatFlags to draw vertical and right-to-left text
Note
Using the Alignment property will remove the effect of StringFormatFlags.DirectionRightToLeft;.
5.4.4 Setting Digital Substitution
The SetDigitSubstitution method can be used to substitute digits in a string on the basis of a user's local area. SetDigitSubstitution takes a parameter of the StringDigitSubstitute enumeration, the members of which are described in Table 5.12.
Member |
Description |
---|---|
National |
Provides substitution digits based on the national language of the user's locale. |
None |
Disables substitutions. |
Traditional |
Provides substitution digits based on user's native script or language. |
User |
Provides a user-defined substitution. |
GDI+: The Next-Generation Graphics Interface
Your First GDI+ Application
The Graphics Class
Working with Brushes and Pens
Colors, Fonts, and Text
Rectangles and Regions
Working with Images
Advanced Imaging
Advanced 2D Graphics
Transformation
Printing
Developing GDI+ Web Applications
GDI+ Best Practices and Performance Techniques
GDI Interoperability
Miscellaneous GDI+ Examples
Appendix A. Exception Handling in .NET