gpt4 book ai didi

java - 如何使用java fx将线连接到圆(而不是中心)

转载 作者:行者123 更新时间:2023-12-01 09:46:03 25 4
gpt4 key购买 nike

我正在使用javafx我不会将一条线连接到2个圆,连接必须是到圆的表面而不是中心

当圆圈移动时,线连接到圆圈中的最佳点。连接时线与圆不能重叠

谢谢

编辑

我正在寻找的解决方案需要这样做

  1. 直线与圆相交,因此切线不是解
  2. 如果直线实际上是连续的,它必须与圆心相交

最佳答案

假设仅使用 centerXcenterY 属性修改位置,只需向这些属性添加监听器即可完成此操作。

可以通过使用圆心在另一个圆心方向平移等于半径的距离来确定线的端点。

请注意,这不会考虑笔划宽度:

public static Point2D getDirection(Circle c1, Circle c2) {
return new Point2D(c2.getCenterX() - c1.getCenterX(), c2.getCenterY() - c1.getCenterY()).normalize();
}

public static void connect(Circle c1, Circle c2, Line line) {
InvalidationListener startInvalidated = observable -> {
Point2D dir = getDirection(c1, c2);
Point2D diff = dir.multiply(c1.getRadius());
line.setStartX(c1.getCenterX() + diff.getX());
line.setStartY(c1.getCenterY() + diff.getY());
};
InvalidationListener endInvalidated = observable -> {
Point2D dir = getDirection(c2, c1);
Point2D diff = dir.multiply(c2.getRadius());
line.setEndX(c2.getCenterX() + diff.getX());
line.setEndY(c2.getCenterY() + diff.getY());
};
c1.centerXProperty().addListener(startInvalidated);
c1.centerYProperty().addListener(startInvalidated);
c1.radiusProperty().addListener(startInvalidated);

startInvalidated.invalidated(null);

c2.centerXProperty().addListener(endInvalidated);
c2.centerYProperty().addListener(endInvalidated);
c2.radiusProperty().addListener(endInvalidated);

endInvalidated.invalidated(null);
}

@Override
public void start(Stage primaryStage) {
Circle c1 = new Circle(100, 100, 50, null);
c1.setStroke(Color.BLUE);

Circle c2 = new Circle(200, 200, 50, null);
c2.setStroke(Color.RED);

Line line = new Line();

connect(c1, c2, line);

Pane pane = new Pane(line, c1, c2);

// demonstrate update during movement
Timeline timeline = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(c1.centerXProperty(), 100)),
new KeyFrame(Duration.ZERO, new KeyValue(c1.centerYProperty(), 100)),
new KeyFrame(Duration.seconds(1), new KeyValue(c1.centerXProperty(), 300)),
new KeyFrame(Duration.seconds(1), new KeyValue(c1.centerYProperty(), 50)),
new KeyFrame(Duration.ZERO, new KeyValue(c2.centerXProperty(), 200)),
new KeyFrame(Duration.ZERO, new KeyValue(c2.centerYProperty(), 200)),
new KeyFrame(Duration.seconds(1), new KeyValue(c2.centerXProperty(), 100)),
new KeyFrame(Duration.seconds(1), new KeyValue(c2.centerYProperty(), 100))
);

timeline.setCycleCount(Animation.INDEFINITE);
timeline.setAutoReverse(true);

timeline.play();

Scene scene = new Scene(pane, 500, 500);

primaryStage.setScene(scene);
primaryStage.show();
}

如果您使用较大的笔画宽度,则可能需要考虑它们......

请注意,如果用完全不透明的涂料填充圆圈并且不修改混合效果,整个问题会变得容易得多,因为线条后面的圆圈将导致圆圈绘制在线条之上在这种情况下,这意味着连接中心就足够了。

关于java - 如何使用java fx将线连接到圆(而不是中心),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38027635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com