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.
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 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.
TABLE 5.9: StringAlignment members
public partial class Form1 : Form
private void Form1_Paint(object sender, PaintEventArgs e)
//Create a Graphics object
Graphics g = this.CreateGraphics();
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);
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 a string
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);
new SolidBrush(Color.White), rect1, strFormat1);
new SolidBrush(Color.Red), rect2, strFormat2);
//Disposes of objects