矩形和从中心点绘制的线之间的截距

时间:2017-08-18 03:31:10

标签: java geometry line rectangles

考虑下图 enter image description here

假设A是矩形和原点的中心点,以及B的坐标,你如何找到AB线与矩形相交的点? 感谢。

2 个答案:

答案 0 :(得分:2)

相对于中心的交点坐标(A点):

all.equal(res, desired_output)
# Error in equal_data_frame(target, current, ignore_col_order = ignore_col_order,  : 
#   Can't join on 'bar' x 'bar' because of incompatible types (list / list)

答案 1 :(得分:0)

我建议使用JTS拓扑套件(https://github.com/locationtech/jts):

// create a rectangle from center point, width and height
public static LinearRing createRectangle(Coordinate center, double width, double height){
    Coordinate upperLeft = new Coordinate(center.x - (width/2), center.y + (height/2));
    Coordinate upperRight = new Coordinate(center.x + (width/2), center.y + (height/2));
    Coordinate lowerRight = new Coordinate(center.x + (width/2), center.y - (height/2));
    Coordinate lowerLeft = new Coordinate(center.x - (width/2), center.y - (height/2));
    LinearRing rectangle = new GeometryFactory().createLinearRing(new Coordinate[]{upperLeft, upperRight, lowerRight, lowerLeft, upperLeft});
    return rectangle;
}

// calculate intersection
public static Coordinate getIntersectionFromRectangleCenterAndCoordinate(LinearRing rectangle, Coordinate someCoord){
    // get your rectangle center coordinate (A)
    Coordinate rectangleCenter = rectangle.getCentroid().getCoordinate();
    // create line from center to someCoord (A - B)
    LineString lineFromCenterToSomeCoord = new GeometryFactory().createLineString(new Coordinate[]{rectangleCenter, someCoord});
    // calculate intersection
    Geometry intersectionGeom = rectangle.intersection(lineFromCenterToSomeCoord);
    // in your case just one intersection point...
    Coordinate intersectionCoordinate = intersectionGeom.getCoordinate();
    return intersectionCoordinate;
}