我只想在鼠标移动事件上绘制一个矩形。我刚刚在MouseDown事件中保存了起始点,Ending Point来自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时,矩形没有绘制......任何人都帮我这个
答案 0 :(得分: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);
答案 1 :(得分: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));