c# - 在图片框上绘制矩形 - 如何限制矩形的面积?

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

绘制矩形后我可以捕获它的内部,并保存为 jpg。

我的问题是什么?

我可以在图片框区域之外绘制边框:

enter image description here

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

对不起我的英语,我希望你能理解我的问题:) 因此,我想要这样的东西:

enter image description here

最佳答案

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

关于c# - 在图片框上绘制矩形 - 如何限制矩形的面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181127/

相关文章:

c# - tinyMce activeeditor 在回发时为空

c# - 如果找到自闭标签,如何删除元素

C# 服务 - OnStart() v 构造函数

c# - 构建 winforms C# 解决方案

c# - 在此 C# 代码中,符号 "=>"在我的方法之后做什么?

javascript - 在Node.js中使用edge.js处理C#.NET事件以获取 Electron

c# - 如何将文件拖放到应用程序中?

c# - C# Winforms 应用程序中总进程内存使用量的自相矛盾的报告

vb.net - Windows Media Player 持续时间 - WinForms

c# - 将多个 DataBindings 添加到 Winforms 标签