Share via


Drawing A Line

To draw a line in GDI+, you need a Graphics object and a Pen object. The Graphics object provides the DrawLine method, and the Pen object holds attributes of the line, such as color and width. The Pen object is passed as an argument to the DrawLine method.

The following example draws a line from (0, 0) to (100, 100). It consists of the class LineForm, which inherits from the .NET Frameworks Form class. The Form class encapsulates the code necessary to create and display a window.

The LineForm class consists of an overridden OnPaint method and a Main method. The Main method calls the Run method of the Application object to create an instance of the LineForm object and display it as a window. The GDI+ code that draws the line to the screen is contained in the OnPaint method.

The OnPaint method receives a PaintEventArgs object from the system when the method is called in response to a Paint event (a Paint event occurs when the form must be redrawn; for example, when the form is moved or resized). The PaintEventArgs object has as one of its members a Graphics object associated with the form. The OnPaint method assigns this Graphics object to g.

The OnPaint method then creates a Pen object. The one argument passed to the Pen constructor is the system-defined color Color.Black.

The OnPaint method then creates two Point objects, which represent the endpoints of the line to be drawn.

Finally, the OnPaint method calls the Graphics.DrawLine method to draw a line to the screen. The arguments passed to the DrawLine method are the Pen object and the two Point objects.

Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Text

Public Class LineForm
   Inherits Form

   Protected Overrides Sub OnPaint(ByVal e as PaintEventArgs)
      Dim g As Graphics
      g = e.Graphics
      Dim blackPen As new Pen(Color.Black, 3)
      Dim startPoint As new Point(0, 0)
      Dim endPoint As new Point(100, 100)
      g.DrawLine(blackPen, startPoint, endPoint)
   End Sub

   Shared Sub Main()
      Application.Run(new LineForm())
   End Sub

End Class

[C#]
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

public class LineForm : Form 
{
   protected override void OnPaint(PaintEventArgs e)
   {
      Graphics g = e.Graphics;
      Pen blackPen = new Pen(Color.Black, 3);
      Point startPoint = new Point(0, 0);
      Point endPoint = new Point(100, 100);
      g.DrawLine(blackPen, startPoint, endPoint);
   }

   public static void Main()
   {
      Application.Run(new LineForm());
   }

}