Share via


Drawing A String

The topic Drawing a Line shows how to write a Windows application that uses GDI+ to draw a line. To draw a string, replace the OnPaint function shown in that topic with the following OnPaint function:

Protected Overrides Sub OnPaint(ByVal e as PaintEventArgs)
      Dim g As Graphics
      g = e.Graphics
      Dim blackBrush as new SolidBrush(Color.Black)
      Dim familyName as new FontFamily("Times New Roman")
      Dim myFont as new Font(familyName, 24, FontStyle.Regular, GraphicsUnit.Pixel)
      Dim startPoint as new PointF(10.0, 20.0)

      g.DrawString("Hello World!", myFont, blackBrush, startPoint)
   End Sub

[C#]
protected override void OnPaint(PaintEventArgs e)
   {
      Graphics g = e.Graphics;
      Brush blackBrush = new SolidBrush(Color.Black);
      FontFamily familyName = new FontFamily("Times New Roman");
      Font myFont = new Font(familyName, 24, FontStyle.Regular, GraphicsUnit.Pixel); 
      PointF startPoint = new PointF(10, 20);
      
      g.DrawString("Hello World!", myFont, blackBrush, startPoint);
   }

The preceding code creates several GDI+ objects. The Graphics object provides the DrawString method, which does the actual drawing. The SolidBrush object specifies the color of the string.

The one argument passed to the SolidBrush constructor is a system-defined property of the Color object that represents opaque black.

The FontFamily constructor receives a single string argument that identifies the font family. The FontFamily object is the first argument passed to the Font constructor. The second argument passed to the Font constructor specifies the font size, and the third argument specifies the style. The value Regular is a member of the FontStyle enumeration. The last argument passed to the Font constructor specifies that the size of the font (24 in this case) is measured in pixels. The value Pixel is a member of the GraphicsUnit enumeration.

The first argument passed to the DrawString method is the string to be drawn, and the second argument is the Font object. The third argument is a Brush object that specifies the color of the string. The last argument is a PointF object that holds the location where the string is drawn.