如何使用 JavaFX 获取一条线上每个点的数组?

How can I get an array of every point on a Line with JavaFX?

我有一条线,点在 (x1, y1)(x2, y2)。 我需要的是一种方法,它只会 return 它们之间的每个点,以整数为增量。

例如,从 (0, 20)(0, 40) 的行会给我 [(0, 20), (0, 21), (0, 22), ..., (0, 39), (0, 40))

如有任何帮助,我们将不胜感激!

假设Line是水平的或垂直的并且有int个坐标,你可以使用IntStream:

public static int[][] getPoints(Line line) {

    int startX = (int) Math.round(line.getStartX());
    int endX = (int) Math.round(line.getEndX());

    int startY = (int) Math.round(line.getStartY());
    int endY = (int) Math.round(line.getEndY());
    
    if (startX != endX && startY != endY) {
        throw new IllegalArgumentException("Line must be horizontal or vetical");
    }
    
    return IntStream.rangeClosed(startX, endX).boxed()
        .flatMap(x -> IntStream.rangeClosed(startY, endY)
                .mapToObj(y -> new int[]{x, y})).toArray(int[][]::new);
}

然后:

Line line = new Line(0, 20, 0, 40);

int[][] points = getPoints(line);
    
System.out.println(Arrays.deepToString(points));

输出:

[[0, 20], [0, 21], [0, 22], [0, 23], [0, 24], [0, 25], [0, 26], [0, 27], [0, 28], [0, 29], [0, 30], [0, 31], [0, 32], [0, 33], [0, 34], [0, 35], [0, 36], [0, 37], [0, 38], [0, 39], [0, 40]]