I have a panel with multiple picturebox created at runtime.
The user will create a rectangle on any picture box and the selected part will be displayed on a preview picturebox.
I have successfully done the above using the below code.
Question
- I want to clear the selection rectangle at mouseup event. Used invalidate but not working. From how to clear the graphics(rectangle shape) in picturebox
Also, when I scroll the panel the same rectangle(mouse selection) is shown on all picturebox.
private void Picture_Paint(object sender, PaintEventArgs e) { if (Rect!=null && Rect.Width>0 && Rect.Height>0) { e.Graphics.FillRectangle(selectionBrush, Rect); } } private void Picture_MouseDown(object sender, MouseEventArgs e) { RecStartpoint = e.Location; ((PictureBox)sender).Invalidate(); } private void Picture_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; Point tempEndPoint = e.Location; Rect.Location = new Point( Math.Min(RecStartpoint.X, tempEndPoint.X), Math.Min(RecStartpoint.Y, tempEndPoint.Y)); Rect.Size = new Size( Math.Abs(RecStartpoint.X - tempEndPoint.X), Math.Abs(RecStartpoint.Y - tempEndPoint.Y)); ((PictureBox)sender).Invalidate(); } private void Picture_MouseUp(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; PictureBox org_pic = (PictureBox)(sender); Point RecEndpoint=e.Location; int xDown = Math.Min(RecStartpoint.X,RecEndpoint.X); int yDown = Math.Min(RecStartpoint.Y, RecEndpoint.Y); int xUp = Math.Max(RecStartpoint.X,RecEndpoint.X); int yUp = Math.Max(RecStartpoint.Y,RecEndpoint.Y); Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); xDown = xDown * org_pic.Image.Width / org_pic.Width; yDown = yDown * org_pic.Image.Height / org_pic.Height; xUp = xUp * org_pic.Image.Width / org_pic.Width; yUp = yUp * org_pic.Image.Height / org_pic.Height; rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); pictureBox_preview_photo.Refresh(); Bitmap sourceBitmap = new Bitmap(org_pic.ImageLocation); Graphics g = pictureBox_preview_photo.CreateGraphics(); g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox_preview_photo.Width, pictureBox_preview_photo.Height), rectCropArea, GraphicsUnit.Pixel); }
I would try this approach:
First, make
Image
variable, in the scope of formsecond, save current picture in that variable on
MouseDown
lastly, on the end of
MouseUp
event, setRectangle
's width and height to zero and restore saved, original imageI didn't understand that second question.