Reputation: 2311
I have two points created, like a line. I want to convert it as a rectangle. How should I do it?
For example this is how I draw the line. But I want it to be a Rectangle
private PointF start, end;
protected override void OnMouseDown(MouseEventArgs e)
{
start.X = e.X;
start.Y = e.Y;
}
protected override void OnMouseUp(MouseEventArgs e)
{
end.X = e.X;
end.Y = e.Y;
Invalidate();
}
Upvotes: 6
Views: 7020
Reputation: 5294
A more clear version of Jon's answer using FromLTRB:
/// <summary>
/// Creates a rectangle based on two points.
/// </summary>
/// <param name="p1">Point 1</param>
/// <param name="p2">Point 2</param>
/// <returns>Rectangle</returns>
public static RectangleF GetRectangle(PointF p1, PointF p2)
{
float top = Math.Min(p1.Y, p2.Y);
float bottom = Math.Max(p1.Y, p2.Y);
float left = Math.Min(p1.X, p2.X);
float right = Math.Max(p1.X, p2.X);
RectangleF rect = RectangleF.FromLTRB(left, top, right, bottom);
return rect;
}
Upvotes: 9
Reputation: 1499800
How about:
new RectangleF(Math.Min(start.X, end.X),
Math.Min(start.Y, end.Y),
Math.Abs(start.X - end.X),
Math.Abs(start.Y - end.Y));
Basically this makes sure you really do present the upper-left corner as the "start", even if the user has created a line from the bottom-left to top-right corners.
Upvotes: 23