C# 在xna/monogame中将2个矢量2点转换为矩形

C# 在xna/monogame中将2个矢量2点转换为矩形,c#,xna,monogame,rectangles,vector-graphics,C#,Xna,Monogame,Rectangles,Vector Graphics,我有一些代码可以检测点击和拖动动作的起点和终点,并将其保存为2个矢量2个点。然后,我使用此代码转换: public Rectangle toRect(Vector2 a, Vector2 b) { return new Rectangle((int)a.X, (int)a.Y, (int)(b.X - a.X), (int)(b.Y - a.Y)); } 上面的代码不起作用,谷歌搜索,到目前为止还没有定论。 有人能给我提供一些代码或公式来正确转换吗? 注:矢量2有x和y,矩形有x、y、

我有一些代码可以检测点击和拖动动作的起点和终点,并将其保存为2个矢量2个点。然后,我使用此代码转换:

public Rectangle toRect(Vector2 a, Vector2 b)
{
    return new Rectangle((int)a.X, (int)a.Y, (int)(b.X - a.X), (int)(b.Y - a.Y));
}
上面的代码不起作用,谷歌搜索,到目前为止还没有定论。 有人能给我提供一些代码或公式来正确转换吗?
注:矢量2有x和y,矩形有x、y、宽度和高度


感谢您的帮助!谢谢

我想你需要有额外的逻辑来决定哪个向量用作左上角,哪个向量用作右下角

试试这个:

    public Rectangle toRect(Vector2 a, Vector2 b)
    {
        //we need to figure out the top left and bottom right coordinates
        //we need to account for the fact that a and b could be any two opposite points of a rectangle, not always coming into this method as topleft and bottomright already.
        int smallestX = (int)Math.Min(a.X, b.X); //Smallest X
        int smallestY = (int)Math.Min(a.Y, b.Y); //Smallest Y
        int largestX = (int)Math.Max(a.X, b.X);  //Largest X
        int largestY = (int)Math.Max(a.Y, b.Y);  //Largest Y

        //calc the width and height
        int width = largestX - smallestX;
        int height = largestY - smallestY;

        //assuming Y is small at the top of screen
        return new Rectangle(smallestX, smallestY, width, height);
    }

您正在寻找
smallestY
,但代码
intsmallesty=(int)Math.Min(a.X,b.X)哪个是incorrect@MickyD编辑以更正错误,感谢您发现了该错误!