javafx - JavaFX 路径:不需要的行
问题描述
我正在尝试使用 JavaFX 绘制一条带有转弯的赛道。
我通过在我的 GraphicsContext 上绘制带有路径的形状来划定车道。
问题是我从来没有让 arcTo 工作,所以我使用 arc ,据我所知,它总是逆时针绘制,这使得我的转弯变得困难,这是我得到的最好结果:
innerRadius
是中心到 (x1, y1)radius
的距离,是中心到 (x0, y0) 的距离。
这是我的代码:
gc.beginPath();
gc.moveTo(x1, y1);
gc.lineTo(x0, y0);
gc.arc(centerX, centerY, radius, radius, startAngle, arcLength);
gc.lineTo(x3, y3);
gc.arc(centerX, centerY, innerRadius, innerRadius, startAngle, arcLength);
gc.closePath();
我不知道如何使路径不包括从 (x2, y2) 到 (x1, y1) 的线。我宁愿坚持使用 arc,但如果你知道如何让 arcTo 使用我拥有的变量,请继续。
谢谢。
解决方案
问题出在这一行:
gc.arc(centerX, centerY, innerRadius, innerRadius, startAngle, arcLength);
这里的起始角度是“向下”,并且应该按照绘制外圆弧的方式逆时针绘制圆弧。尽管需要对弧使用不同的参数,但您希望以相反的方向绘制弧:
gc.arc(centerX, centerY, innerRadius, innerRadius, startAngle + arcLength, -arcLength);
您还可以摆脱其中一个lineTo
s,因为closePath
会自动连接到路径的开头。
@Override
public void start(Stage stage) {
Canvas canvas = new Canvas(400, 400);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setStroke(Color.BLACK);
gc.setFill(Color.LIGHTGRAY);
final double centerX = 100;
final double centerY = 200;
final double dR = 20;
final double radius = (350 - centerY) / 2;
final double innerRadius = radius - dR;
final double x0 = centerX;
final double y0 = centerY + radius;
final double x3 = x0 + innerRadius;
final double y3 = centerY;
final double startAngle = 270;
final double arcLength = 90;
gc.beginPath();
gc.moveTo(x0, y0);
gc.arc(centerX, centerY, radius, radius, startAngle, arcLength);
gc.lineTo(x3, y3);
gc.arc(centerX, centerY, innerRadius, innerRadius, startAngle + arcLength, -arcLength);
gc.closePath();
gc.fill();
gc.stroke();
Scene scene = new Scene(new StackPane(canvas));
stage.setScene(scene);
stage.show();
}