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)的直線。