绘制如图:
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//MyPoint1, MyPoint2表示鼠标按下和弹起时鼠标的坐标位置
public Point MyPoint1, MyPoint2;
//是否绘制
public int MyFlag = 0;
//GDI+
Graphics g = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "当前坐标点:X=" + 0.ToString() + ",Y=" + 0.ToString();
g = this.CreateGraphics();
this.BackColor = Color.WhiteSmoke;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
//当鼠标弹起时,设置MyFlag = 0,表示不能画线
this.MyFlag = 0;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
this.Text = "当前坐标点:X=" + e.X.ToString() + ",Y=" + e.Y.ToString();
//使绘图质量最高,即消除锯齿
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.High;
g.CompositingQuality = CompositingQuality.HighQuality;
Pen MyPen = new Pen(Color.Black, 3.0F);
//MyFlag=0表示鼠标弹起,不能进行画线
//当鼠标按下时,设置MyFlag=1表示可以画线
if (this.MyFlag == 0)
return;
//鼠标移动,每次变换时,MyPoint2都记录下鼠标的位置,以便进行鼠标移动画线
this.MyPoint2.X = e.X;
this.MyPoint2.Y = e.Y;
g.DrawLine(MyPen, MyPoint1, MyPoint2);
//当画完一条线后(很短的,可以当做一个小点看待),将MyPoint1的坐标重置为此时鼠标的位置
MyPoint1.X = e.X;
MyPoint1.Y = e.Y;
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
//鼠标第一次按下时,设置鼠标坐标为第一个点的坐标
this.MyFlag = 1;
this.MyPoint1.X = e.X;
this.MyPoint1.Y = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
g.Clear(Color.WhiteSmoke);
}
private void Form1_Resize(object sender, EventArgs e)
{
g = this.CreateGraphics();
}
private void button1_Click(object sender, EventArgs e)
{
g.Clear(Color.WhiteSmoke);
}
}
}
参考原文:https://blog.csdn.net/hui_shixu/article/details/7738410