Do these two rectangles overlap vertically? - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Description

Do these two rectangles overlap vertically?

Demo Code

// All rights reserved.
//package com.java2s;
import java.awt.*;

public class Main {
    /**/*from   w w w . java  2 s.c  om*/
     * Private utility method.  Do these two rectangles overlap vertically? <p>
     * NOTE:  This method will still return true if the two rectangles are positioned
     * beside each other even though they don't completely overlap.
     */
    private static boolean rectanglesOverlapping_YAxis(Rectangle rec1,
            Rectangle rec2) {
        boolean bOverlapping = false;
        if ((rec1 == null) || (rec2 == null)) {
            return false;
        }
        int nTop1 = (int) (rec1.getY());
        int nBottom1 = (int) (rec1.getY()) + (int) (rec1.getHeight());
        int nTop2 = (int) (rec2.getY());
        int nBottom2 = (int) (rec2.getY()) + (int) (rec2.getHeight());
        // Find the intersections. If two lines coming from a rectangle corner
        // both have intersection points then there IS overlap.
        boolean bTop1_Intersects = false;
        boolean bBottom1_Intersects = false;
        boolean bTop2_Intersects = false;
        boolean bBottom2_Intersects = false;
        // Are there intersections based on rectangle #1?
        if ((nTop1 > nTop2) && (nTop1 < nBottom2)) {
            bTop1_Intersects = true;
        }
        if ((nBottom1 > nTop2) && (nBottom1 < nBottom2)) {
            bBottom1_Intersects = true;
        }
        // Are there intersections based on rectangle #2?
        if ((nTop2 > nTop1) && (nTop2 < nBottom1)) {
            bTop2_Intersects = true;
        }
        if ((nBottom2 > nTop1) && (nBottom2 < nBottom1)) {
            bBottom2_Intersects = true;
        }
        // Do we overlap or not?
        if (bTop1_Intersects || bTop2_Intersects || bBottom1_Intersects
                || bBottom2_Intersects) {
            bOverlapping = true;
        }
        return bOverlapping;
    }
}

Related Tutorials