C# 如何实现鼠标绘图
运行效果

窗体代码
public partial class Form1 : Form { public Form1() { InitializeComponent(); } Point P1, P2; Rectangle 矩形; List<Rectangle> 矩形集 = new List<Rectangle>(); Pen 钢笔; List<Pen> 钢笔集 = new List<Pen>(); Random 随机数 = new Random(); bool 鼠标按下 = false; float 钢笔粗细 = 2.0f; private void Form1_Load(Object sender, EventArgs e) { DoubleBuffered = true; MouseWheel += Form1_MouseWheel; } private void Form1_MouseWheel(Object sender, MouseEventArgs e) { if (e.Delta > 0) { 钢笔粗细 += 1f; if (钢笔粗细 > 10f) { 钢笔粗细 = 10f; } } else { 钢笔粗细 -= 1f; if (钢笔粗细 < 1f) { 钢笔粗细 = 1f; } } Text = "钢笔粗细:" + ((int)钢笔粗细).ToString(); } private void Form1_MouseDown(Object sender, MouseEventArgs e) { P1 = new Point(e.X, e.Y); 矩形 = new Rectangle(); 钢笔 = new Pen(Color.FromArgb(Rnd(96, 160), Rnd(0, 255), Rnd(0, 255), Rnd(0, 255)), 钢笔粗细); 鼠标按下 = true; } private void Form1_MouseUp(Object sender, MouseEventArgs e) { 鼠标按下 = false; 矩形集.Add(矩形); 钢笔集.Add(钢笔); } private void Form1_Paint(Object sender, PaintEventArgs e) { var g = e.Graphics; if (鼠标按下) { g.DrawRectangle(钢笔, 矩形); } if (矩形集.Count > 0) { for (int i = 0; i < 矩形集.Count; i++) { Pen t钢笔 = 钢笔集[i]; Rectangle t矩形 = 矩形集[i]; if (t钢笔 != null && t矩形.Width > 0 && t矩形.Height > 0) { g.DrawRectangle(t钢笔, t矩形); } } } } private void Form1_MouseMove(Object sender, MouseEventArgs e) { if (鼠标按下 == true) { P2 = new Point(e.X, e.Y); 矩形 = 框选(P1, P2); Refresh(); } } public int Rnd(int minNum, int maxNum) { int k = 0; if (minNum < 0) { k = -minNum; } return 随机数.Next(minNum - k, maxNum - k + 1); } public static Rectangle 框选(Point p1, Point p2) { int x = Math.Min(p1.X, p2.X); int y = Math.Min(p1.Y, p2.Y); int w = (p2.X - p1.X); if (w < 0) { w = -w; } int h = (p2.Y - p1.Y); if (h < 0) { h = -h; } return new Rectangle(x, y, w, h); } }

浙公网安备 33010602011771号