溫馨提示×

C# Graphics.DrawLine()函數(shù)實例講解

c#
小億
134
2023-12-19 02:38:09
欄目: 編程語言

Graphics.DrawLine()函數(shù)用于在指定的兩個點之間繪制一條直線。

下面是一個使用Graphics.DrawLine()函數(shù)繪制直線的示例:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // 創(chuàng)建畫筆和繪圖表面
        Pen pen = new Pen(Color.Black);
        Graphics g = e.Graphics;

        // 定義起點和終點坐標
        int x1 = 50, y1 = 50;
        int x2 = 200, y2 = 200;

        // 使用DrawLine()函數(shù)繪制直線
        g.DrawLine(pen, x1, y1, x2, y2);

        // 釋放資源
        pen.Dispose();
        g.Dispose();
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(300, 300);
        this.Name = "Form1";
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }
}

在這個示例中,我們創(chuàng)建了一個繼承自Form類的窗體類Form1,并重載了Form1的Paint事件處理函數(shù)Form1_Paint。在Form1_Paint事件處理函數(shù)中,我們創(chuàng)建了一個畫筆對象和一個繪圖表面對象。然后,我們定義了起點坐標(x1, y1)和終點坐標(x2, y2)。最后,我們使用Graphics.DrawLine()函數(shù)繪制一條直線。

在Main函數(shù)中,我們創(chuàng)建了Form1對象并將其傳遞給Application.Run()函數(shù)以運行應用程序。

運行這個示例,將會在窗體上繪制一條從坐標(50, 50)到坐標(200, 200)的直線。

0