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

Java 矩形和从中心点绘制的直线之间的截距,java,geometry,line,rectangles,Java,Geometry,Line,Rectangles,考虑下图 假设A是矩形的中心点和原点,以及B的坐标,如何找到直线AB与矩形相交的点? 谢谢。相对于中心(点)的交点坐标: dx=B.X-A.X dy=B.Y-A.Y 如果宽度*Abs(dy)

考虑下图

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

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

dx=B.X-A.X
dy=B.Y-A.Y
如果宽度*Abs(dy)<高度*Abs(dx),则
x=符号(dx)*宽度/2
y=dy*x/dx
其他的
y=标志(dy)*高度/2
x=dx*y/dy

我建议使用JTS拓扑套件():


我投票将这个问题作为离题题来结束,因为这是一个几何问题。我在哪里可以问几何问题?试试math.stackexchange.com,但在问问题之前,请确保先参观他们。另外,请不要在与java无关的问题上使用“java”标记。
dx = B.X - A.X
dy = B.Y - A.Y
if Width * Abs(dy) < Height * Abs(dx) then
   x = Sign(dx) * Width / 2
   y = dy * x / dx
else
   y = Sign(dy) * Height / 2
   x = dx * y / dy
// 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;
}