Working with Text and Strings in GDI+


This article has been excerpted from book "Graphics Programming with GDI+".

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    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.gif

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.

bookGDI.jpg

This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.

Up Next
    Ebook Download
    View all
    Learn
    View all