How to create a RectangleF using two PointF?

蓝咒 提交于 2019-12-10 14:53:14

问题


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();
    }

回答1:


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.




回答2:


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;
    }


来源:https://stackoverflow.com/questions/4103943/how-to-create-a-rectanglef-using-two-pointf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!