5

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();
    }
Rye
  • 2,273
  • 9
  • 34
  • 43

2 Answers2

22

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

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;
    }
Pedro77
  • 5,176
  • 7
  • 61
  • 91