Java Rectangle Intersect intersect(Rectangle r1, Rectangle r2, Rectangle result)

Here you can find the source of intersect(Rectangle r1, Rectangle r2, Rectangle result)

Description

More efficient version of Sun's Rectangle intersection() method

License

BSD License

Declaration

static Rectangle intersect(Rectangle r1, Rectangle r2, Rectangle result) 

Method Source Code

//package com.java2s;
/*****************************************************************************
 * Copyright (C) 2006, Jon Meyer, Ben Bederson and Jean-Daniel Fekete        *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the BSD Software License    *
 * a copy of which has been included with this distribution in the           *
 * license-agile2d.txt file.                                                 *
 *****************************************************************************/

import java.awt.Rectangle;

public class Main {
    /**/*from w w w  . java2s  .  c o m*/
    *  More efficient version of Sun's Rectangle intersection() method
     */
    static Rectangle intersect(Rectangle r1, Rectangle r2, Rectangle result) {
        int x1 = max(r1.x, r2.x);
        int x2 = min(r1.x + r1.width, r2.x + r2.width);
        int y1 = max(r1.y, r2.y);
        int y2 = min(r1.y + r1.height, r2.y + r2.height);

        if (((x2 - x1) < 0) || ((y2 - y1) < 0))
            // Width or height is negative. No intersection.
            result.x = result.y = result.width = result.height = 0;
        else {
            result.x = x1;
            result.y = y1;
            result.width = x2 - x1;
            result.height = y2 - y1;
        }
        return result;
    }

    private static int max(int a, int b) {
        return (a > b ? a : b);
    }

    private static int min(int a, int b) {
        return (a < b ? a : b);
    }
}

Related

  1. getMaxIntersection(List targetRects, Rectangle rect)
  2. intersect(Rectangle rect1, Rectangle rect2)
  3. intersection(Line2D.Double line, Rectangle2D.Double bounds)
  4. intersection(Rectangle r1, Rectangle r2, Rectangle out)
  5. intersection(Rectangle rectangle, Rectangle rectangle1, Rectangle rectangle2)