2

我只是想在鼠标移动事件上画一个矩形。我刚刚将起点保存在 MouseDown 事件中,而终点来自 Mouse Move 。并调用了paintImage函数。

Rectangle rec = new Rectangle (x1,y1,x2 - x1 , y2 - y1);
G.DrawRectangle(Pens.Blue,rec);

Starting Points = (x1,y1)
Ending Points = (x2,y2)

问题是当 x2 的值小于 x1 或 y2 小于 y1 时,矩形没有绘制......任何人都可以帮助我

4

2 回答 2

2

你可以很容易地写一张支票:

int drawX, drawY, width, height;
if (x1 < x2)
{
    drawX = x1;
    width = x2 - x1;
}
else
{
    drawX = x2;
    width = x1 - x2;
}

if (y1 < y2)
{
    drawY = y1;
    height = y2 - y1;
}
else
{
    drawY = y2;
    height = y1 - y2;
}

Rectangle rec = new Rectangle (drawX, drawY, width, height);
G.DrawRectangle(Pens.Blue,rec);

这也可以写成更短的形式:

Rectangle rec = new Rectangle ((x1 < x2) ? x1 : x2, (y1 < y2) ? y1 : y2, (x1 < x2) ? x2 - x1 : x1 - x2, (y1 < y2) ? y2 - y1 : y1 - y2);
G.DrawRectangle(Pens.Blue,rec);
于 2012-07-10T07:15:14.117 回答
2

如果宽度变为负数,您需要交换坐标:

int xpos = (x2-x1 < x1) ? x2 : x1;
int ypos = (y2-y1 < y1) ? y2 : y1;
int width = Math.Abs(x2-x1);
int height = Math.Abs(y2-y1);

G.DrawRectangle(Pens.Blue, new Rectangle(xpos, ypos, width, height));
于 2012-07-10T07:15:24.833 回答