Rotate Rectangle in Java

前端 未结 2 2058
孤城傲影
孤城傲影 2020-12-11 20:18

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 b

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 21:04

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

提交回复
热议问题