画在一个MouseMove
这样在 WinForms 中不会很顺利。
在调整矩形大小之前,您基本上需要对矩形的引用。
我添加了以下代码来跟踪矩形和 8 个可拖动点:
private Point GetHandlePoint(int value) {
Point result = Point.Empty;
if (value == 1)
result = new Point(areaRect.Left, areaRect.Top);
else if (value == 2)
result = new Point(areaRect.Left, areaRect.Top + (areaRect.Height / 2));
else if (value == 3)
result = new Point(areaRect.Left, areaRect.Bottom);
else if (value == 4)
result = new Point(areaRect.Left + (areaRect.Width / 2), areaRect.Top);
else if (value == 5)
result = new Point(areaRect.Left + (areaRect.Width / 2), areaRect.Bottom);
else if (value == 6)
result = new Point(areaRect.Right, areaRect.Top);
else if (value == 7)
result = new Point(areaRect.Right, areaRect.Top + (areaRect.Height / 2));
else if (value == 8)
result = new Point(areaRect.Right, areaRect.Bottom);
return result;
}
private Rectangle GetHandleRect(int value) {
Point p = GetHandlePoint(value);
p.Offset(-2, -2);
return new Rectangle(p, new Size(5, 5));
}
以下是我修改表单代码的方法:
private Rectangle areaRect = new Rectangle(100, 100, 300, 300);
private Rectangle oldRect;
private int dragHandle = 0;
private Point dragPoint;
public Form1() {
InitializeComponent();
this.DoubleBuffered = true;
}
protected override void OnMouseDown(MouseEventArgs e) {
for (int i = 1; i < 9; i++) {
if (GetHandleRect(i).Contains(e.Location)) {
dragHandle = i;
oldRect = areaRect;
dragPoint = GetHandlePoint(i);
}
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
if (dragHandle == 1) {
// to do
} else if (dragHandle == 2) {
int diff = dragPoint.X - e.Location.X;
areaRect = new Rectangle(oldRect.Left - diff, oldRect.Top, oldRect.Width + diff, oldRect.Height);
} else if (dragHandle == 7) {
int diff = dragPoint.X - e.Location.X;
areaRect = new Rectangle(oldRect.Left, oldRect.Top, oldRect.Width - diff, oldRect.Height);
}
if (dragHandle > 0)
this.Invalidate();
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e) {
dragHandle = 0;
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.DrawRectangle(Pens.Red, areaRect);
for (int i = 1; i < 9; i++) {
e.Graphics.FillRectangle(Brushes.DarkRed, GetHandleRect(i));
}
base.OnPaint(e);
}
发布的代码仅执行第 #2 点和第 #7 点,但这应该为您提供一些可以使用的逻辑。我确信这段代码可以改进,它只是一个工作示例。