首页 > 解决方案 > 创建一个矩形与给定线的所有交点的列表

问题描述

所以我有一个完成的工作函数,可以找到交点和一个矩形类。我想创建所有这些点的列表。

你能建议我怎么做吗?谢谢。

public class Rectangle {

private double width;
private double height;
private Point upperLeft;

// Create a new rectangle with location and width/height.
public Rectangle(Point upperLeft, double width, double height){
    this.upperLeft = upperLeft;
    this.width = width;
    this.height = height
}

// Return a (possibly empty) List of intersection points
// with the specified line.
public java.util.List<Point> intersectionPoints(Line line){
    //**I don't know
}

}

我正在考虑创建 2 个 4 个数组。

Line[] rectLines = new Line[4];
    Point[] IntersectionPoints = new Point[4];

然后根据矩形角创建 4 条线并将它们添加到数组中。

rectLines[0] = new Line(rect.getUpperLeft().getX(), rect.getUpperLeft().getY(), rect.getWidth(), rect.getUpperLeft().getY());
    rectLines[1] = new Line(rect.getUpperLeft().getX(), rect.getUpperLeft().getY(), rect.getUpperLeft().getX(), rect.getHeight());
    rectLines[2] = new Line(rect.getUpperLeft().getX(), rect.getHeight(), rect.getWidth(), rect.getHeight());
    rectLines[3] = new Line(rect.getWidth(), rect.getUpperLeft().getY(), rect.getWidth(), rect.getHeight());

然后运行一个循环,添加使用我的交点查找器函数并找到点并将它们添加到点的数组中。

for (int i=0; i<4; i++) {
        if (intersectionWith(rectLines[i]) != null)
            IntersectionPoints[i] = intersectionWith(rectLines[i]);}

intersectionWith ”函数如果没有交点则返回NULL,如果有点则ad返回该点。

但现在呢?我怎样才能使它成为一个列表?您认为将点的数组大小定义为 4 是否明智,尽管我真的不知道它是 0、1、2、3 还是 4?那么阵列中未使用的插槽会发生什么?

ps如果线穿过一个角落会发生什么?这意味着它将有 2 个交点,因为它将与 2 个矩形边相交。

谢谢。

标签: javalinepointrectanglesintersect

解决方案


推荐阅读