Combine these two rectangles into one rectangle that encompasses both - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Description

Combine these two rectangles into one rectangle that encompasses both

Demo Code

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

public class Main {
    /**//ww w  .j a v  a2  s .  c om
     * Utility method.  Combine these two rectangles into one rectangle that encompasses both.
     */
    public static Rectangle combineRectangles(Rectangle rec1, Rectangle rec2) {
        if ((rec1 != null) && (rec2 != null)) {
            int nLeft = (int) Math.min(rec1.getX(), rec2.getX());
            int nTop = (int) Math.min(rec1.getY(), rec2.getY());
            int nWidth = ((int) Math.max(rec1.getX() + rec1.getWidth(),
                    rec2.getX() + rec2.getWidth())) - nLeft;
            int nHeight = ((int) Math.max(rec1.getY() + rec1.getHeight(),
                    rec2.getY() + rec2.getHeight())) - nTop;
            return new Rectangle(nLeft, nTop, nWidth, nHeight);
        } else if (rec1 != null) {
            // Just return rec1.
            return rec1;
        } else if (rec2 != null) {
            // Just return rec2.
            return rec2;
        } else {
            return null;
        }
    }
}

Related Tutorials