I need to create rectangles that are rotated around their center (so they don't need to be parallel to the axes of the coordinate system). So basicelly each rectangle can be defined by center-X, center-Y, width, height and angle. What I want to do then is to perform calculations on whether certain points are contained in these rectangles or not (so no drawing will be involved). I guess I cant use the Rectangle2D
class because these rectangles will always be parallel to the x and y-axis of the coordinate system. Is the only way to get this functionality by writing my own rectangle class or is there anything existing (similar to Rectangle2D
) I can use?
Asked
Active
Viewed 1.7k times
4

gaussd
- 899
- 6
- 15
- 28
-
1I get the impression you're describing the solution you found to a certain problem. It might be a good idea to also explain what particular problem you're trying to solve. Chances are, there exist proven solutions/algorithms for that problem already. – Bart Kiers Nov 10 '10 at 14:51
-
I want to simulate smart antennas. So the center of each rectangle is a node (with several smart antennas). The rectangle then is the simplified signal pattern. Which means that the rectangles will be rotated so that they point in the direction of the receiver node. Then i want to calculate if certain antennas are in the signal pattern/rectangle which could be disturbed by this signal. Therefore i need a method for calculating if a point is contained in a rectangle. – gaussd Nov 10 '10 at 14:59
2 Answers
5
Rotate all the points you want to test and use contains(Point) method of the Rectangle2D as Mihai did.
But if you really want to rotate the rectangles you can do it like this (this is the integer version but probably you can do it with Rectangle2D aswell :)).
public class TestRotate {
public static void main(String... args) {
Rectangle r = new Rectangle(50, 50, 100, 100);
Point check = new Point(100, 151); // clearly outside
System.out.println("first: " + r.contains(check));
AffineTransform at = AffineTransform.getRotateInstance(
Math.PI/4, r.getCenterX(), r.getCenterY());
Polygon p = new Polygon();
PathIterator i = r.getPathIterator(at);
while (!i.isDone()) {
double[] xy = new double[2];
i.currentSegment(xy);
p.addPoint((int) xy[0], (int) xy[1]);
System.out.println(Arrays.toString(xy));
i.next();
}
// should now be inside :)
System.out.println("second: " + p.contains(check));
}
}

dacwe
- 43,066
- 12
- 116
- 140
3
You can use Rectangle2D to check for containment, if instead of rotating your rectangle by an angle, say, counterclockwise, you rotate each of the points you need to check by the same angle clockwise, relative to the center of the rectangle. Something like
double dx = point.x - rectangleCenter.x;
double dy = point.y - rectangleCenter.y;
double newX = rectangleCenter.x - dx*Math.cos(angle) + dy*Math.sin(angle);
double newY = rectangleCenter.x - dx*Math.sin(angle) - dy*Math.cos(angle);

Mihai
- 2,835
- 2
- 28
- 36