在picturebox上绘制矩形 - 如何限制矩形区域?

Elf*_*foc 5 c# winforms

我在带有鼠标事件的图片框上绘制矩形:

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();     
    }
Run Code Online (Sandbox Code Playgroud)

绘制矩形后,我可以捕获它,并保存为jpg.

我的问题是什么?

我可以绘制边框在picturebox区域之外的边框:

在此输入图像描述

如何限制图片框边框的矩形区域是矩形的最大允许位置?

对不起,我的英文,我希望你能理解我的问题:)所以我希望有这样的东西:

在此输入图像描述

Lar*_*ech 2

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();     
}
Run Code Online (Sandbox Code Playgroud)