简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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