虽然这有点旧,但这是此类任务的第一个(据我所知也是唯一有用的)结果。
我已经使用上述示例来增强和实施经过测试的解决方案。就我而言,我还想让矩形严格位于另一个矩形内。具体来说,我在 PictureBox 中绘制它,我希望它永远不会超出图片之外。这就是 max_width 和 max_height 对应的内容。
请注意,有时它有点有趣 - 当在某些方向上达到最小尺寸时,它会在另一个方向上重新调整尺寸。我决定我喜欢这种行为,并且它应该是一个功能。:)
protected void pictureBox1_OnMouseMove(object sender, MouseEventArgs e)
{
// Where I started - where I stopped
int x_diff = dragPoint.X - e.Location.X;
int y_diff = dragPoint.Y - e.Location.Y;
// Minimum values
int small_offset = 5;
int left = small_offset;
int top = small_offset;
int width = small_offset;
int height = small_offset;
// Max values
int max_width = this.pictureBox1.Image.Width;
int max_height = this.pictureBox1.Image.Height;
if (dragHandle == 1)
{
left = Math.Max(oldRect.Left - x_diff, left);
top = Math.Max(oldRect.Top - y_diff, top);
width = Math.Min(Math.Max(oldRect.Width + x_diff, width), max_width - left - small_offset);
height = Math.Min(Math.Max(oldRect.Height + y_diff, height), max_height - top - small_offset);
}
else if (dragHandle == 2)
{
left = Math.Max(oldRect.Left - x_diff, left);
top = oldRect.Top;
width = Math.Min(Math.Max(oldRect.Width + x_diff, width), max_width - left - small_offset);
height = oldRect.Height;
}
else if (dragHandle == 3)
{
left = Math.Max(oldRect.Left - x_diff, left);
top = oldRect.Top;
width = Math.Min(Math.Max(oldRect.Width + x_diff, width), max_width - left - small_offset);
height = Math.Min(Math.Max(oldRect.Height - y_diff, height), max_height - top - small_offset);
}
else if (dragHandle == 4)
{
left = oldRect.Left;
top = Math.Max(oldRect.Top - y_diff, top);
width = oldRect.Width;
height = Math.Min(Math.Max(oldRect.Height + y_diff, height), max_height - top - small_offset);
}
else if (dragHandle == 5)
{
left = oldRect.Left;
top = oldRect.Top;
width = oldRect.Width;
height = Math.Min(Math.Max(oldRect.Height - y_diff, height), max_height - top - small_offset);
}
else if (dragHandle == 6)
{
left = oldRect.Left;
top = Math.Max(oldRect.Top - y_diff, top);
width = Math.Min(Math.Max(oldRect.Width - x_diff, width), max_width - left - small_offset);
height = Math.Min(Math.Max(oldRect.Height + y_diff, height), max_height - top - small_offset);
}
else if (dragHandle == 7)
{
left = oldRect.Left;
top = oldRect.Top;
width = Math.Min(Math.Max(oldRect.Width - x_diff, width), max_width - left - small_offset);
height = oldRect.Height;
}
else if (dragHandle == 8)
{
left = oldRect.Left;
top = oldRect.Top ;
width = Math.Min(Math.Max(oldRect.Width - x_diff, width), max_width - left - small_offset);
height = Math.Min(Math.Max(oldRect.Height - y_diff, height), max_height - top - small_offset);
}
if (dragHandle > 0)
{
areaRect = new Rectangle(left, top, width, height);
this.Invalidate();
}
}