Java Rectangle Intersect intersects(final Rectangle2D a, final Rectangle2D b)

Here you can find the source of intersects(final Rectangle2D a, final Rectangle2D b)

Description

intersects

License

Open Source License

Declaration

public static boolean intersects(final Rectangle2D a, final Rectangle2D b) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.Shape;

import java.awt.geom.Area;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Rectangle2D;

public class Main {
    public static boolean intersects(final Rectangle2D a, final Rectangle2D b) {
        return Math.abs(a.getCenterX() - b.getCenterX()) < a.getWidth() * 0.5 + b.getWidth() * 0.5
                && Math.abs(a.getCenterY() - b.getCenterY()) < a.getHeight() * 0.5 + b.getHeight() * 0.5;
    }/*from  w w  w  .ja  v a2  s. c  o m*/

    public static boolean intersects(final Ellipse2D a, final Ellipse2D b) {
        if (a.getWidth() != a.getHeight() || b.getWidth() != b.getHeight()) {
            return shapeIntersects(a, b);
        }

        double distSq = Math.pow((a.getCenterX() - b.getCenterX()), 2)
                + Math.pow((a.getCenterY() - b.getCenterY()), 2);
        double radSumSq = Math.pow((a.getWidth() / 2.0 + b.getWidth() / 2.0), 2);

        if (distSq > radSumSq) {
            return false;
        }

        return true;
    }

    /**
     * Shape intersects. WARNING: USE THIS METHOD WITH CAUTION BECAUSE IT IS A
     * VERY SLOW WAY OF CALCULATING INTERSECTIONS.
     *
     * @param shapeA
     *          the shape a
     * @param shapeB
     *          the shape b
     * @return true, if successful
     */
    public static boolean shapeIntersects(final Shape shapeA, final Shape shapeB) {
        if (!shapeA.getBounds2D().intersects(shapeB.getBounds2D())) {
            return false;
        }

        if (shapeA instanceof Rectangle2D && shapeB instanceof Rectangle2D) {
            return ((Rectangle2D) shapeA).intersects((Rectangle2D) shapeB);
        }

        final Area areaA = new Area(shapeA);
        areaA.intersect(new Area(shapeB));
        return !areaA.isEmpty();
    }
}

Related

  1. intersectRect(double x1, double y1, double w1, double h1, double x2, double y2, double w2, double h2)
  2. intersects(double oldx, double oldy, double oldwidth, double oldheight, double oldx2, double oldy2, double oldwidth2, double oldheight2)
  3. intersects(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
  4. intersects(final float x, final float y, final float z, final int sx, final int sy, final int sz)
  5. intersects(final Rectangle elementRect, final Rectangle viewportRect)
  6. intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
  7. intersects(Point p1, Point p2, Rectangle rect)
  8. intersects(Rectangle aRectangle, Line2D aLine)
  9. intersects(Rectangle rect1, Rectangle rect2, boolean vertical)