Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing rectangle on picturebox - how to limit area of rectangle?

Tags:

c#

winforms

i'm drawing rectangle on picturebox with mouse events:

private void StreamingWindow_MouseDown(object sender, MouseEventArgs e)
    {
              rect = new Rectangle(e.X, e.Y, 0, 0);
              this.Invalidate();       
    }

    private void StreamingWindow_Paint(object sender, PaintEventArgs e)
    {

       if (painting == true)
        {

            using (Pen pen = new Pen(Color.Red, 2))
            {
                e.Graphics.DrawRectangle(pen, rect);
            }
        }
    }

    private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)
    {       
           if (e.Button == MouseButtons.Left)
           {
               // Draws the rectangle as the mouse moves
               rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
           }
           this.Invalidate();     
    }

After drawing rectangle i can capture inside of it, and save as jpg.

What's my problem?

I can draw retangle which borders are outside area of picturebox:

enter image description here

How can i limit area of rectangle that border of picturebox is max allowed location of rectangle?

Sorry for my english, i hope you'll understand my problem :) So as a result i'd like to have something like this:

enter image description here

like image 669
Elfoc Avatar asked Nov 04 '22 15:11

Elfoc


1 Answers

private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)
{       
  if (e.Button == MouseButtons.Left)
  {
    // Draws the rectangle as the mouse moves
    rect = new Rectangle(rect.Left, rect.Top, Math.Min(e.X - rect.Left, pictureBox1.ClientRectangle.Width - rect.Left), Math.Min(e.Y - rect.Top, pictureBox1.ClientRectangle.Height - rect.Top));
  }
  this.Invalidate();     
}
like image 98
LarsTech Avatar answered Nov 15 '22 06:11

LarsTech