2016-08-06 20 views
1

所以我有这个计划,需要测试两个矩形,并检查:如何检查两个矩形几何形状之间的空间关系中使用Java

  1. 如果测试矩形为参考矩形
  2. 如果测试矩形内被重叠的基准矩形
  3. 如果测试矩形仅与参考矩形
  4. IF测试矩形和参考矩形是不同的共享边界

参考矩形和测试矩形都以其中心坐标(x,y)及其宽度和高度定义。

我相信我有正确的第一个检查编码,但我无法弄清楚重叠,共享边界和完全不同的最后三个检查的数学。

这里是我的四个检查,到目前为止的代码:

//returns true if the specified rectangle is inside this rectangle 
    public boolean contains(MyRectangle2D r){ 
      if(this.x > r.x + r.width && x + width < r.x && y > r.y +r.height     && y + height < r.y){ 
     return true; 
    } 
    else{ 
     return false; 
    } 
    } 

    //returns true if the specified rectangle overlaps with this rectangle 
    public boolean overlaps(MyRectangle2D r) { 
    if (this.x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y){ 
     return true; 
    } 
    else{ 
     return false; 
    } 
    } 

    //returns true if only the boundaries touch 
    public boolean abut(MyRectangle2D r) { 
     if(this.x = r.x + r.width && x + width = r.x || y = r.y +r.height && y + height = r.y){ 
     return true; 
    } 
    else{ 
     return false; 
    } 
} 

    //returns true if the rectangles are not touching at all 
    public boolean distinct(MyRectangle2D r) { 

    } 

回答

0

您可以使用的Java Topolygy套房(JTS):

  • 首先,你可以用你的参数创建矩形使用org.locationtech.jts.util.GeometricShapeFactoryAPI):
  • 然后,您可以使用定义的空间关系(within,overlaps,...)org.locationtech.jts.geom.GeometryAPI

Simple代码:

// method to create your rectangles like before (Polygon objects) 
public static Polygon createPolygon(Coordinate center, double width, double height){ 
    GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); 
    shapeFactory.setNumPoints(4); 
    shapeFactory.setCentre(center); 
    shapeFactory.setWidth(width); 
    shapeFactory.setHeight(height); 
    return shapeFactory.createRectangle(); 
} 

public static void main(String[] args) { 

    // create your rectagles 
    Polygon rectangleA = createPolygon(new Coordinate(0, 0), 5, 10); 
    Polygon rectangleB = createPolygon(new Coordinate(2, 0), 5, 10); 

    // ### check your constraints 
    // 1. rectangle is within the reference rectangle 
    boolean bWithinA = rectangleB.within(rectangleA); // false 

    // 2. rectangle is overlapping the reference rectangle 
    boolean bOverlappingA = rectangleB.overlaps(rectangleA); // true 

    // 3. rectangle is only sharing a border with the reference rectangle 
    boolean bSharesBorderA = rectangleB.touches(rectangleA); // false 

    // 4. rectangle and reference rectangle are distinct 
    boolean bDistinctsA = rectangleB.disjoint(rectangleA); // false 
} 
相关问题