How to create a RectangleF using two PointF?

I have two points created as a string. I want to convert it as a rectangle. How should I do it?

For example, I draw a line. But I want it to beRectangle

    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();
    }
+5
source share
2 answers

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

This basically ensures that you truly represent the top left corner as a “start”, even if the user created a line from the bottom left to the top right.

+16
source

A clearer version of John'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;
    }
+2
source

All Articles