C# Graphics.DrawLine函数实例讲解

发布时间:2025-12-09 11:46:10 浏览次数:1

Graphics.DrawLine()方法用于绘制连接由坐标对指定的两个点的线。此方法的重载列表中有4种方法,如下所示:

  • DrawLine(Pen, PointF, PointF) Method
  • DrawLine(Pen, Int32, Int32, Int32, Int32) Method
  • DrawLine(Pen, Single, Single, Single, Single) Method
  • DrawLine(Pen, Point, Point) Method

首先,在Set-1中已经讨论了两种方法。在这里,我们将讨论最后两种方法。



DrawLine(Pen, Single, Single, Single, Single) Method

此方法用于绘制线形式的一组指定坐标,这些坐标以离散形式x1,y1,x2,y2给出。

用法:

public void DrawLine (System.Drawing.Pen pen, float x1, float y1, float x2, float y2);

参数:

  • pen:Pen确定线条的颜色,宽度和样式。
  • x1:第一点的横坐标。
  • y1:第一点的纵坐标。
  • x2:第二点的横坐标。
  • y2:第二点的纵坐标。

异常:如果pen为null,则此方法将提供ArgumentNullException。

例:

// C# program to illustrate the use of  using System; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms;   namespace GFG {   class PrintableForm:Form {       // Main Method     public static void Main()     {         Application.Run(new PrintableForm());     }       public PrintableForm()     {         ResizeRedraw = true;     }       protected override void OnPaint(PaintEventArgs pea)     {         // Defines the Pen         Pen pen = new Pen(ForeColor);           // x1 = 30         // y1 = 30         // x2 = 200         // y2 = 300                   // using the Method         pea.Graphics.DrawLine(pen, 30.0F, 30.0F, 200.0f, 300.0f);     } } }

输出:

DrawLine(Pen, Point, Point)

此方法用于从指定的点集到指定的点集画一条线。它需要一个Point变量,该变量由(x,y)点组成。

用法:



public void DrawLine (System.Drawing.Pen pen, System.Drawing.PointF pt1, System.Drawing.PointF pt2);

参数:

  • pen:Pen确定线条的颜色,宽度和样式。
  • pt1:将(x,y)坐标定义为初始点的Point变量。
  • pt2:将(x,y)坐标定义为最终点的Point变量。

异常:如果pen为null,则此方法将提供ArgumentNullException。

例:

// C# program to demonstrate the use of // DrawLine(Pen, Point, Point) Method using System; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms;   namespace GFG {   class PrintableForm:Form {       // Main Method     public static void Main()     {         Application.Run(new PrintableForm());     }       public PrintableForm()     {         ResizeRedraw = true;     }       protected override void OnPaint(PaintEventArgs pea)     {         // Defines pen         Pen pen = new Pen(ForeColor);           // Defines the both points to connect         // pt1 is (30, 30) which represents (x1, y1)         Point pt1 = new Point(30, 30);           // pt1 is (200, 300) which represents (x2, y2)         Point pt2 = new Point(200, 300);           // Draws the line         pea.Graphics.DrawLine(pen, pt1, pt2);     } } }

输出:




drawline
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477