RasterRect { public static final RasterRect intersection( RasterRect first, RasterRect second ) { int fmaxX = first.x + first.width; int smaxX = second.x + second.width; int fmaxY = first.y + first.height; int smaxY = second.y + second.height; if ( second.x >= fmaxX || smaxX <= first.x || second.y >= fmaxY || smaxY <= first.y ) { return null; } int x = Math.max( first.x, second.x ); int y = Math.max( first.y, second.y ); int width = Math.min( smaxX, fmaxX ) - x; int height = Math.min( smaxY, fmaxY ) - y; return new RasterRect( x, y, width, height ); } RasterRect( int x, int y, int width, int height );  RasterRect();  RasterRect( Rectangle rect );  RasterRect( RasterRect rasterRect ); @Override String toString(); @Override boolean equals( Object other ); @Override int hashCode(); static final RasterRect intersection( RasterRect first, RasterRect second ); public int x; public int y; public int width; public int height; }
@Test public void intersectionOverlap() { RasterRect first = new RasterRect( 2, 2, 2, 2 ); RasterRect second = new RasterRect( 1, 3, 4, 5 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertEquals( 2, result.x ); Assert.assertEquals( 3, result.y ); Assert.assertEquals( 2, result.width ); Assert.assertEquals( 1, result.height ); }
@Test public void intersectionTotal() { RasterRect first = new RasterRect( 2, 2, 4, 4 ); RasterRect second = new RasterRect( 3, 3, 2, 2 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertEquals( 3, result.x ); Assert.assertEquals( 3, result.y ); Assert.assertEquals( 2, result.width ); Assert.assertEquals( 2, result.height ); }
@Test public void intersectionTotal2() { RasterRect first = new RasterRect( 3, 3, 2, 2 ); RasterRect second = new RasterRect( 2, 2, 4, 4 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertEquals( 3, result.x ); Assert.assertEquals( 3, result.y ); Assert.assertEquals( 2, result.width ); Assert.assertEquals( 2, result.height ); }
@Test public void outsideLeft() { RasterRect first = new RasterRect( 2, 2, 2, 2 ); RasterRect second = new RasterRect( 0, 3, 1, 5 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertNull( result ); }
@Test public void outsideRight() { RasterRect first = new RasterRect( 2, 2, 2, 2 ); RasterRect second = new RasterRect( 5, 3, 1, 5 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertNull( result ); }
@Test public void outsideTop() { RasterRect first = new RasterRect( 2, 2, 2, 2 ); RasterRect second = new RasterRect( 2, 0, 5, 2 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertNull( result ); }
@Test public void outsideBottom() { RasterRect first = new RasterRect( 2, 2, 2, 2 ); RasterRect second = new RasterRect( 2, 5, 5, 2 ); RasterRect result = RasterRect.intersection( first, second ); Assert.assertNull( result ); }