Graphics.DrawLine()函数用于在指定的两个点之间绘制一条直线。它的使用方法如下:
Graphics graphics = this.CreateGraphics(); // 创建一个控件的Graphics对象
Pen pen = new Pen(Color.Black, 2); // 创建一个黑色、宽度为2的画笔
graphics.DrawLine(pen, 10, 10, 100, 100); // 在点(10, 10)到点(100, 100)之间绘制一条直线
pen.Dispose(); // 释放画笔对象
graphics.Dispose(); // 释放Graphics对象
完整的示例代码如下:
using System;
using System.Drawing;
using System.Windows.Forms;
public class DrawLineExample : Form
{
public DrawLineExample()
{
this.Size = new Size(300, 300);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Black, 2);
graphics.DrawLine(pen, 10, 10, 100, 100);
pen.Dispose();
graphics.Dispose();
}
public static void Main()
{
Application.Run(new DrawLineExample());
}
}
运行该示例代码,会在窗体上绘制一条从点(10, 10)到点(100, 100)的直线。