C# 画第二个矩形时,第一个矩形会消失,怎么办。
源代码如下
- C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WindowsFormsApplication2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Point sp = new Point(0, 0); private Point ep = new Point(0, 0); private bool d1 = false; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (!d1) { sp=new Point(e.X,e.Y); ep=new Point(e.X,e.Y); } d1 = !d1; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (!d1) { return; } ep = new Point(e.X, e.Y); this.pictureBox1.Refresh(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { ColorDialog cd = new ColorDialog(); if (cd.ShowDialog() == DialogResult.OK) { MessageBox.Show(cd.Color.Name); } Pen pen1 = new Pen(cd, 3); if (sp.Equals(ep)) return; int a = ep.Y - sp.Y; int b = ep.X - sp.X; e.Graphics.DrawRectangle(pen1, sp.X,sp.Y,b,a); } }}
[解决办法]
看看这个效果,注册 PictureBox 的 MouseDown MouseUp Paint 3个事件,对应下面的方法,鼠标先在 PictureBox 上按下,按住移动一段距离,再放开,选择个颜色,画出一个矩形
- C# code
using System;using System.Collections.Generic;using System.Drawing;using System.Windows.Forms;namespace CommonPlatform{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Point sp = Point.Empty; private List<object[]> rects = new List<object[]>(); private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { this.sp = e.Location; } private void pictureBox1_Paint(object sender, PaintEventArgs e) { foreach (var item in this.rects) { Rectangle r = (Rectangle)item[0]; Color c = (Color)item[1]; e.Graphics.DrawRectangle(new Pen(c), r); } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { if (sp.IsEmpty && sp == e.Location) { return; } int x = e.X > sp.X ? sp.X : e.X; int y = e.Y > sp.Y ? sp.Y : e.Y; int width = Math.Abs(sp.X - e.X); int height = Math.Abs(sp.Y - e.Y); ColorDialog dialog = new ColorDialog(); dialog.ShowDialog(this); this.rects.Add(new object[] { new Rectangle(x, y, width, height), dialog.Color }); this.pictureBox1.Invalidate(); this.sp = Point.Empty; } }}
[解决办法]
不要跟踪OnPaint事件,直接在mousemove事件中做几件事:
1.invalidate鼠标上次经过的点与sp形成的矩形;
2.绘制由当前鼠标坐标与sp形成的新矩形