2 Replies Latest reply: Aug 6, 2011 2:42 PM by 880576 RSS


      Hi all,

      Does anybody know how to determine whether two arbitrarily rotated rectangles are contained within each other? The contains method works when two rectangles are aligned to the same axis, but I can't see how to do this after both rectangles undergo an affine transform.

      Let's say I have an outer rectangle named rect1 which contains the rectangle named rect2.
      Rectangle rect1 = new Rectangle(20,20,300,100);
      Rectangle rect2 = new Rectangle(50,30,100,20);
      I can rotate both rectangles with an affine transformation but the contains method will not work on the two transformed shapes.
      AffineTransform af1 = new AffineTransform();
      af1.rotate(Math.toRadians(45), (20+300)/2, (20+100)/2);
      Shape rotRect2 = af1.createTransformedShape(rect1);
      AffineTransform aft = new AffineTransform();
      af2.rotate(Math.toRadians(45), (50+200)/2, (30+20)/2);
      Shape rotRect2 = af1.createTransformedShape(rect2);
      It would be ideal to do something like:
      Any pointers in the right direction would be appreciated.

      Edited by: 877573 on Aug 6, 2011 12:41 PM
        • 1. Re: java.awt.Rectangle
          (First of all... I assume it's a typo in your example code that you're rotating the same shape twice? It looks like you intend to rotate each rect separately.)

          Anyway... the various contains() methods are written to work with rectangular bounds for performance reasons. If that doesn't work for you, you can use Area, although it's more computationally expensive. If you subtract Area A from Area B and the resulting area is empty, then B must be fully enclosed within A.

          For example:
          final Rectangle rect1 = new Rectangle(20,20,300,100);
          final Rectangle rect2 = new Rectangle(50,30,100,20);
                   Shape s1 = rect1;
                   Shape s2 = rect2;
                   if (rotated) {
                      AffineTransform af1 = new AffineTransform();
                      af1.rotate(Math.toRadians(45), (20+300)/2, (20+100)/2);
                      s1 = af1.createTransformedShape(rect1);
                      AffineTransform af2 = new AffineTransform();
                      af2.rotate(Math.toRadians(45), (50+200)/2, (30+20)/2);
                      s2 = af2.createTransformedShape(rect2);
                   final Area a1 = new Area( s1 );
                   final Area a2 = new Area( s2 );
                   a2.subtract( a1 );
                   a1.subtract( new Area( s2 ) );
                   System.out.println( "area1 contains a2 = " +  a2.isEmpty() );
                   System.out.println( "area2 contains a1 = " +  a1.isEmpty() );
          • 2. Re: java.awt.Rectangle
            Hi 872883,

            Thanks for the quick response. Your solution worked perfectly!