如何在C#中用鼠标选择PictureBox.Image上的区域

我只是想在我的picturebox.image上做一个选择,但这比一些有点烦人的情况变得更糟。 我想到了主要图片框上的另一个图片框,但它对我来说似乎很懒散。 我需要知道是否有一种方法可以在picturebox.image上创建一个选择区域(它将是半透明的蓝色区域),我将用鼠标绘制它并且它不应该改变我正在处理的图像。

样品:

// 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 = new Rectangle( Math.Min(RectStartPoint.X, tempEndPoint.X), Math.Min(RectStartPoint.Y, tempEndPoint.Y), Math.Abs(RectStartPoint.X - tempEndPoint.X), Math.Abs(RectStartPoint.Y - tempEndPoint.Y)); Invalidate(Rect); } // Draw Area // private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { // Draw the rectangle... if (pictureBox1.Image != null) { Brush brush = new SolidBrush(Color.FromArgb(128, 72, 145, 220)); e.Graphics.FillRectangle(brush, Rect); } } 

我用你的代码,你差不多就在那里。 您需要使pictureBox1而不是矩形无效。 我还添加了一个Rect的检查,因此当它没有初始化或没有大小时它不会被绘制。

另一个重要的变化:我只创建了一次Rectangle,并调整了它的位置和大小。 减少垃圾清理!

编辑

我为Rectangle添加了一个鼠标右键单击处理程序。

 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.Right) { if (Rect.Contains(e.Location)) { Debug.WriteLine("Right click"); } } }