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' start point (upper-left corner), their size(width+height) and their angle. Because of the rotation, the start point is not necessarely the upper-left corner, but that does not matter here. Then when I click the picturebox, I need to check in which rectangle (if any) I have clicked.
So I need some way of checking if a point is in a rectangle, but I also need to take into account the rotation of each rectangle. Does anybody know of a way to do this in C#?
In this post, we have discussed a new approach. Approach: If we observe carefully, It will be clear that for a point to be lie inside the rectangle, it should be lie inside the x-coordinate (x1, x2) of the rectangle as well as it should also lie inside the y-coordinate (y1, y2) of the rectangle.
If most of the points aren't even close to the rectangle performing a simple distance check (e.g. (point.x - firstCorner.x) > aLargeDistance) might result in a large speedup, while it might even slow things down if almost all of the points are inside the rectangle.
Now if the point is within 64, 64 you know you hit the rectangle. More specifically I was checking a pixel of a rotated image to make sure I hit a pixel of a specific color.
A rotated rectangle consists of four points, the corners. Therefore it should be possible to convert it to a contour. Then I would suggest you follow the answer on StackOverflow, linked below, to see if your point is within that contour.
Is it possible to apply the same rotation applied to the rectangle to the point in reverse?
For example, Rectangle A is rotated 45 degrees clockwise from its origin (upper left corner), you would then just rotate point B around the same origin 45 degrees COUNTER clockwise, then check to see if it falls within Rectangle A pre-rotation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With