🎨

Graphics.DrawLine Method Overview

Jun 17, 2025

Overview

This lecture explains the Graphics.DrawLine method from the System.Drawing namespace in .NET, covering its purpose, overloads, parameters, usage, and exceptions.

Purpose and Definition

  • The Graphics.DrawLine method draws a line connecting two specified points.
  • It is used in GDI+ drawing for Windows Forms and other .NET graphics contexts.

Method Overloads

  • There are four main overloads of DrawLine:
    • DrawLine(Pen, int x1, int y1, int x2, int y2) draws a line between two integer coordinate pairs.
    • DrawLine(Pen, float x1, float y1, float x2, float y2) draws a line between two floating-point coordinate pairs.
    • DrawLine(Pen, Point pt1, Point pt2) draws a line between two Point structures (integer values).
    • DrawLine(Pen, PointF pt1, PointF pt2) draws a line between two PointF structures (floating-point values).

Parameters and Exceptions

  • All overloads require a Pen object, which sets the line's color, width, and style.
  • The start and end points are given as either numeric coordinates or point structures.
  • An ArgumentNullException is thrown if the pen parameter is null.

Example Usage

  • Example code creates a black pen and draws a horizontal line using the provided coordinates or points.
  • These examples are designed for use within a Windows Forms Paint event handler, using PaintEventArgs e.

Platform and Version Support

  • Supported in .NET (versions 8, 9, 10 and above), .NET Framework (1.1 to 4.8.1), .NET Standard (2.0+), and Windows Desktop (3.0 to 10.0).

Key Terms & Definitions

  • Pen — Object specifying the line’s color, width, and style.
  • Point / PointF — Structures representing 2D coordinates using integers (Point) or floats (PointF).
  • ArgumentNullException — Exception thrown when a required argument is null.
  • GDI+ — Microsoft’s graphics device interface used in Windows Forms rendering.

Action Items / Next Steps

  • Review the Using a Pen to Draw Lines and Shapes documentation for more drawing techniques.
  • Practice implementing DrawLine in a sample Windows Forms project.