JAVA计算矩形是否相交、交集面积
一、解决思路
我们分别用p1与p2表示矩形A的左下角和右上角,用p3和p4表示矩形B的左下角和右上角。考虑两个矩形不重叠的情况:
(p1.x > p4.x) || (p2.x < p3.x) || (p1.y > p4.y) || (p2.y < p3.y)
对上述条件取反,即可得到两个矩形重叠的条件。当正向思维比较繁杂时,不妨换种思路,也许会柳暗花明!
二、代码实现
矩形类:Rectangle.java
import java.io.Serializable; public class Rectangle implements Comparable<Rectangle>, Serializable { private double x; //矩形左下角的x坐标 private double y; //矩形左下角的y坐标 private double length; private double width; public Rectangle(double x, double y, double length, double width) { this.x = x; this.y = y; this.length = length; this.width = width; } public double getArea() { return length * width; } public double getX() { return x; } public double getY() { return y; } public double getLength() { return length; } public double getWidth() { return width; } @Override public int compareTo(Rectangle o) { return Double.compare(this.getArea(), o.getArea()); } }
计算两个矩形的重叠面积:OverlapAreaOfRectangle.java
public class OverlapAreaOfRectangle { public double CalculateOverlapArea(Rectangle rect1, Rectangle rect2) { if (rect1 == null || rect2 == null) { return -1; } double p1_x = rect1.getX(), p1_y = rect1.getY(); double p2_x = p1_x + rect1.getLength(), p2_y = p1_y + rect1.getWidth(); double p3_x = rect2.getX(), p3_y = rect2.getY(); double p4_x = p3_x + rect2.getLength(), p4_y = p3_y + rect2.getWidth(); if (p1_x > p4_x || p2_x < p3_x || p1_y > p4_y || p2_y < p3_y) { return 0; } double Len = Math.min(p2_x, p4_x) - Math.max(p1_x, p3_x); double Wid = Math.min(p2_y, p4_y) - Math.max(p1_y, p3_y); return Len * Wid; } public static void main(String[] args) { Rectangle rect1 = new Rectangle(0, 1, 3, 2); Rectangle rect2 = new Rectangle(2, 0, 2, 2); OverlapAreaOfRectangle overlap = new OverlapAreaOfRectangle(); System.out.println(overlap.CalculateOverlapArea(rect1, rect2)); } }