Check if a point is in a rotated rectangle (C#)

前端 未结 7 1525
囚心锁ツ
囚心锁ツ 2021-01-07 22:20

I have a program in C# (Windows Forms) which draws some rectangles on a picturebox. They can be drawn at an angle too (rotated).

I know each of the rectangles\' star

7条回答
  •  旧巷少年郎
    2021-01-07 22:51

    Edit: After looking back, I'm using MonoGame and the OP is using Windows Forms. The following is for MonoGame.

    I've been messing this for a while now and have found a couple answers, just none of them actually worked. Here is a C# function that does exactly as OP describes, if not for OP then other people Googling like I was.

    It was a headache to figure this out. A lot of the typical guesswork.

        bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
        {
            Matrix rotMat = Matrix.CreateRotationZ(-rotation);
            Vector2 Localpoint = P - (rect.Location).ToVector2();
            Localpoint = Vector2.Transform(Localpoint, rotMat);
            Localpoint += (rect.Location).ToVector2();
    
            if (rect.Contains(Localpoint)) { return true; }
            return false;
        }
    

    And here it is in a single line of code. Probably faster to use.

        bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
        {
            return rect.Contains(Vector2.Transform(P - (rect.Location).ToVector2(), Matrix.CreateRotationZ(-rotation)) + (rect.Location).ToVector2());
        }
    

提交回复
热议问题