Draw rectangle with negative coordinates Draw rectangle with negative coordinates windows windows

Draw rectangle with negative coordinates


There are 4 possible ways for the user to drag the mouse to make the rectangle. Only one of them you're happy with right now, from upper-left to lower-right. The other 3 ways produce negative values for the rectangle's Width or Height. You deal with all 4 possibilities like this:

var rc = new Rectangle(    Math.Min(startpoint.x, endpoint.x),     Math.Min(startpoint.y, endpoint.y),    Math.Abs(endpoint.x - startpoint.x),    Math.Abs(endpoint.y - startpoint.y));e.Graphics.FillRectangle(sb, rc);


If the starting X is < the ending X, just swap the values before drawing. Same for the Y coordinates.

if ( start_point.X < end_point.X ){    var oldX = start_point.X;    start_point.X = end_point.X;    end_point.X = oldX;}if ( start_point.Y < end_point.Y ){    var oldY = start_point.Y;    start_point.Y = end_point.Y;    end_point.Y = oldY;}