As we discussed, 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
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs 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 Point(20, 80));
//Dispose of objects
solidBrush.Dispose();
g.Dispose();
}
}
}
FIGURE 5.13: Fonts with different styles and sizes
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.
Conclusion
Hope the article would have helped you in understanding Working with Text and Strings in GDI+. Read other articles on GDI+ on the website.