繁体   English   中英

360度绘制矩形

[英]Drawing rectangles in 360 degrees

我正在制作一个可以绘制矩形的小型绘画应用程序。 但是,除了西南象限以外,我无法在其他任何地方绘制矩形。 我正在使用此绘制矩形:

graphics.DrawRectangle(
    mainPen, 
    prevPoint.X, 
    prevPoint.Y, 
    e.Location.X - prevPoint.X, 
    e.Location.Y - prevPoint.Y);

我只是想念些小东西吗? 还是我必须进行计算以找出在哪里设置原点? 如果这种解释太混乱了,我可以提供图像。

您需要将较小的XY设置为Rectangle's左上角点,将两点之间的绝对差设置为widthheight 您可以使用此:

int left = prevPoint.X < e.Location.X ? prevPoint.X : e.Location.X;
int top = prevPoint.Y < e.Location.Y ? prevPoint.Y : e.Location.Y;
graphics.DrawRectangle(mainPen, left, top, Math.Abs(e.Location.X - prevPoint.X), Math.Abs(e.Location.Y - prevPoint.Y));

如果您转到“东部”,则e.Location.X - prevPoint.X的计算会给您带来负面的影响,因为起点(例如200)小于终点(例如400)。 因此,您要将负整数传递给宽度和高度的方法。

根据规范: http : //msdn.microsoft.com/zh-cn/library/x6hb4eba.aspx,您始终定义矩形的左上角,然后定义(正)宽度和高度。

尝试这个:

graphics.DrawRectangle(
    mainPen, 
    Math.Min(prevPoint.X, e.Location.X), 
    Math.Min(prevPoint.Y, e.Location.Y), 
    Math.Abs(e.Location.X - prevPoint.X), 
    Math.Abs(e.Location.Y - prevPoint.Y)
);

由于该方法期望参数为(左上x,左上y,宽度,高度),因此我假设您需要计算哪个点是矩形的左上点。 将其用作前两个参数,然后通过减去两个点并获取绝对值来计算宽度/高度。

代码应该是这样的:

int leftX, leftY, width, height;
leftX = prevPoint.X < e.Location.X ? prevPoint.X : e.Location.X;
leftY = prevPoint.Y < e.Location.Y ? prevPoint.Y : e.Location.Y;
width = Math.Abs(prevPoint.X - e.Location.X);
height = Math.Abs(prevPoint.Y - e.Location.Y);
graphics.DrawRectangle(mainPen, leftX, leftY, width, height);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM