簡體   English   中英

在picturebox上繪制矩形 - 如何限制矩形區域?

[英]Drawing rectangle on picturebox - how to limit area of rectangle?

我在帶有鼠標事件的圖片框上繪制矩形:

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();     
    }

繪制矩形后,我可以捕獲它,並保存為jpg。

我的問題是什么?

我可以繪制邊框在picturebox區域之外的邊框:

在此輸入圖像描述

如何限制圖片框邊框的矩形區域是矩形的最大允許位置?

對不起,我的英文,我希望你能理解我的問題:)所以我希望有這樣的東西:

在此輸入圖像描述

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();     
}

解決這個問題的另一種方法是防止矩形被淹沒在pictureBox控件之外

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

有人可以發現這個解決方案更有用

我想說實現這一目標的最簡單的方法,我個人認為從UX角度來看更自然,是:在MouseUp檢查矩形的BottomLeft角落是否在圖片框的區域之外,如果是這樣,只需將其“返回”並對齊就像你繪制的那樣,它與圖片框的角度相同

編輯

只是為了讓你知道我在說什么,一個偽代碼

    private void StreamingWindow_MouseUp(object sender, MouseEventArgs e)
    {
              if(rect.Right > myPictureBox.ClientRectangle.Right)
              {
                 rect.Width = myPictureBox.Right - rect.Left - someoffset;                     
              }       
              if(rect.Bottom > myPictureBox.ClientRectangle.Bottom)
              {
                 rect.Height= myPictureBox.Bottom - rect.Top - someoffset;                     
              }       
    }

像這樣的東西。 但你需要檢查一下。

為什么不設置矩形坐標

 rect = new Rectangle(min(e.X, pictureBoxX), min(e.Y, pictureBoxY), 0, 0);

您需要根據圖片框的位置和位置計算pictureX和pictureY。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM