VB.NET中如何在PictureBox左键释放时清除_onPaint绘制的区域?
解决PictureBox左键释放清除绘制矩形的问题
很简单,你只需要在鼠标左键释放的事件里重置绘制的矩形区域,然后刷新PictureBox就能让蓝色标记消失了。
修改步骤:
- 找到
pictureBox1_MouseUp方法,添加左键释放的处理逻辑:当检测到左键松开时,把Rect重置为一个空的Rectangle,然后调用Invalidate()触发重绘,这样Paint事件就不会再绘制这个矩形了。
修改后的完整代码:
private Point RectStartPoint; private Rectangle Rect = new Rectangle(); private Brush selectionBrush = new SolidBrush(Color.FromArgb(128, 72, 145, 220)); // Start Rectangle private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // Determine the initial rectangle coordinates... RectStartPoint = e.Location; Invalidate(); } // Draw Rectangle private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; Point tempEndPoint = e.Location; Rect.Location = new Point( Math.Min(RectStartPoint.X, tempEndPoint.X), Math.Min(RectStartPoint.Y, tempEndPoint.Y)); Rect.Size = new Size( Math.Abs(RectStartPoint.X - tempEndPoint.X), Math.Abs(RectStartPoint.Y - tempEndPoint.Y)); pictureBox1.Invalidate(); } // Draw Area private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { // Draw the rectangle... if (pictureBox1.Image != null) { if (Rect != null && Rect.Width > 0 && Rect.Height > 0) { e.Graphics.FillRectangle(selectionBrush, Rect); } } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { // 重置矩形为空,触发重绘后就不再显示标记 Rect = new Rectangle(); pictureBox1.Invalidate(); } else if (e.Button == MouseButtons.Right) { if (Rect.Contains(e.Location)) { Debug.WriteLine("Right click"); } } }
额外优化(可选):
如果你希望放入新图片时也自动清除矩形,可以在设置pictureBox1.Image的地方添加一行重置代码,比如:
// 假设你是这样设置新图片的 pictureBox1.Image = new Bitmap("新图片路径"); Rect = new Rectangle(); pictureBox1.Invalidate();
这样无论左键释放还是更换图片,蓝色标记都会消失啦!
内容的提问来源于stack exchange,提问作者Petr Klíč
相关产品推荐
相关产品推荐

