日期:2014-05-20  浏览次数:20747 次

java中给定两个长方形的中心点、长度、宽度,如何判断他们是包含关系还是相交关系,如何编写代码,想了很久……
java中给定两个长方形的中心点、长度、宽度,如何判断他们是包含关系还是相交关系,如何编写代码,想了很久……

------解决方案--------------------
swing里面的矩形一般指水平的,查了下api也没用具体给的倾斜的。要是搞倾斜的,再说楼主条件也不够搞成倾斜的。
Java code

import java.awt.Point;
public class Main {
    public static void main(String args[]){
        RectangeDemo r1 = new RectangeDemo(new Point(1,2),5,5);
        RectangeDemo r2 = new RectangeDemo(new Point(10,8),5,5);
        
        checkRelation(r1,r2);
    }

    static class RectangeDemo{
        Point center;
        double width;
        double height;
        
        public RectangeDemo(Point point, int width, int height) {
            this.center = point;
            this.width = width;
            this.height = height;
        }
    }
    
    public static void checkRelation(RectangeDemo r1,RectangeDemo r2){
        if(Math.abs(r1.center.x -r2.center.x) > r1.width + r2.width
                && Math.abs(r1.center.y -r2.center.y) > r1.height + r2.height ){
            System.out.println("相离");
        }
        else if(Math.abs(r1.center.x - r2.center.x) < Math.abs(r1.width - r2.width)
                        && Math.abs(r1.center.y -r2.center.y) > Math.abs(r1.height - r2.height)){
            System.out.println("包含");
        }
        else{
            System.out.println("相交");
        }
    }
}

------解决方案--------------------
纠正一下。sorry
|x1-x2|>(L1+L2)/2&&|y1 - y2|>(H1+H2)/2;相离。
|x1-x2| <|L1-L2|/2 && |y1 - y2|< |H1-H2|/2 包含
其他情况相交。
Java code

import java.awt.Point;
public class Main {
    public static void main(String args[]){
        RectangeDemo r1 = new RectangeDemo(new Point(1,2),5,5);
        RectangeDemo r2 = new RectangeDemo(new Point(10,8),5,5);
        
        checkRelation(r1,r2);
    }

    static class RectangeDemo{
        Point center;
        double width;
        double height;
        
        public RectangeDemo(Point point, int width, int height) {
            this.center = point;
            this.width = width;
            this.height = height;
        }
    }
    
    public static void checkRelation(RectangeDemo r1,RectangeDemo r2){
        if(Math.abs(r1.center.x -r2.center.x) > r1.width/2 + r2.width/2
                && Math.abs(r1.center.y -r2.center.y) > r1.height/2 + r2.height/2 ){
            System.out.println("相离");
        }
        else if(Math.abs(r1.center.x - r2.center.x) < Math.abs(r1.width/2 - r2.width/2)
                        && Math.abs(r1.center.y -r2.center.y) > Math.abs(r1.height/2 - r2.height/2)){
            System.out.println("包含");
        }
        else{
            System.out.println("相交");
        }