简体   繁体   English

360度绘制矩形

[英]Drawing rectangles in 360 degrees

I'm making a small paint application that has the ability to draw rectangles. 我正在制作一个可以绘制矩形的小型绘画应用程序。 However, I cannot draw rectangle anywhere other than the south-west quadrant. 但是,除了西南象限以外,我无法在其他任何地方绘制矩形。 I'm drawing rectangles using this: 我正在使用此绘制矩形:

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

Am I just missing something small? 我只是想念些小东西吗? or do I have to do calculations to figure out where to set the origin? 还是我必须进行计算以找出在哪里设置原点? I can provide images if this explanation is too confusing. 如果这种解释太混乱了,我可以提供图像。

You need to set the smaller X and Y to be your Rectangle's top-left point and absolute difference between the points to be your width and height . 您需要将较小的XY设置为Rectangle's左上角点,将两点之间的绝对差设置为widthheight You could use this: 您可以使用此:

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));

The calculation for e.Location.X - prevPoint.X gives you a negative resilt if you go "East" because the starting point (say 200) is smaller than the ending point (say 400). 如果您转到“东部”,则e.Location.X - prevPoint.X的计算会给您带来负面的影响,因为起点(例如200)小于终点(例如400)。 Thus you are passing in negative integers into the method for width and height. 因此,您要将负整数传递给宽度和高度的方法。

According to the spec: http://msdn.microsoft.com/en-us/library/x6hb4eba.aspx you always define the upper-left corner of the rectangle, and then define a (positive) width and height. 根据规范: http : //msdn.microsoft.com/zh-cn/library/x6hb4eba.aspx,您始终定义矩形的左上角,然后定义(正)宽度和高度。

Try this: 尝试这个:

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)
);

Since the method expects the parameters as (upper left x, upper left y, width, height) I would assume you need to calculate which point is the upper left point of the rectangle. 由于该方法期望参数为(左上x,左上y,宽度,高度),因此我假设您需要计算哪个点是矩形的左上点。 Use that as the first two parameters and then calculate the width/height by subtracting the two points and taking the absolute value. 将其用作前两个参数,然后通过减去两个点并获取绝对值来计算宽度/高度。

Code should be something like this: 代码应该是这样的:

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