C# Graphics.DrawLine()函数实例讲解

   2025-02-13 2610
核心提示:Graphics.DrawLine()函数用于在指定的两个点之间绘制一条直线。下面是一个使用Graphics.DrawLine()函数绘制直线的示例:using Sy

Graphics.DrawLine()函数用于在指定的两个点之间绘制一条直线。

下面是一个使用Graphics.DrawLine()函数绘制直线的示例:

using System;using System.Drawing;using System.Windows.Forms;public class Form1 : Form{    public Form1()    {        InitializeComponent();    }    private void Form1_Paint(object sender, PaintEventArgs e)    {        // 创建画笔和绘图表面        Pen pen = new Pen(Color.Black);        Graphics g = e.Graphics;        // 定义起点和终点坐标        int x1 = 50, y1 = 50;        int x2 = 200, y2 = 200;        // 使用DrawLine()函数绘制直线        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());    }}

在这个示例中,我们创建了一个继承自Form类的窗体类Form1,并重载了Form1的Paint事件处理函数Form1_Paint。在Form1_Paint事件处理函数中,我们创建了一个画笔对象和一个绘图表面对象。然后,我们定义了起点坐标(x1, y1)和终点坐标(x2, y2)。最后,我们使用Graphics.DrawLine()函数绘制一条直线。

在Main函数中,我们创建了Form1对象并将其传递给Application.Run()函数以运行应用程序。

运行这个示例,将会在窗体上绘制一条从坐标(50, 50)到坐标(200, 200)的直线。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言