Java examples for java.lang:Math Geometry Shape
Test if two rectangles intersect.
//package com.java2s; import java.awt.geom.*; public class Main { /**/*from ww w . j a v a2 s .c om*/ * Test if two rectangles intersect. <br> * This test differs from Rectangle2D.intersects()in that it returns also true * if one of the rectangles has an height or a width that equals 0. * @param r1 Rectangle 1 * @param r2 Rectangle 2. * @return true if the two rectangles intersect, false if the rectangles do * not intersect or if they are identical. */ public static boolean rectanglesIntersect(Rectangle2D r1, Rectangle2D r2) { if (r1 == null || r2 == null) { return false; } final double xmin1 = r1.getMinX(); final double xmax1 = r1.getMaxX(); final double xmin2 = r2.getMinX(); final double xmax2 = r2.getMaxX(); final double xmin = xmin1 > xmin2 ? xmin1 : xmin2; final double xmax = xmax1 < xmax2 ? xmax1 : xmax2; if (xmin > xmax) { return false; } final double ymin1 = r1.getMinY(); final double ymax1 = r1.getMaxY(); final double ymin2 = r2.getMinY(); final double ymax2 = r2.getMaxY(); // test if rectangles are identical if (ymin1 == ymin2 && xmin1 == xmin2) { return false; } final double ymin = ymin1 > ymin2 ? ymin1 : ymin2; final double ymax = ymax1 < ymax2 ? ymax1 : ymax2; return (ymin <= ymax); } }