代码如下
public class HeptagonExample extends Application {
@Override
public void start(Stage primaryStage) {
Pane root = new Pane();
Scene scene = new Scene(root, 400, 400);
// 设置七边形的中心点和半径(为了简化,这里我们使用一个矩形区域)
double centerX = 200;
double centerY = 200;
double radius = 100;
// 计算七边形的每个顶点的角度(从0度开始,每个顶点间隔360/7度)
double angleStep = 360.0 / 7.0;
printhh1( centerX, centerY, radius, angleStep, root);
primaryStage.setTitle("JavaFX Heptagon Example");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void printhh1(double centerX,double centerY, double radius,double angleStep,Pane root){
// 初始化第一个顶点的位置(移动到)
// 创建一个Path对象
Path heptagon = new Path();
heptagon.setFill(Paint.valueOf("70B603")); // 设置填充颜色
heptagon.setStroke(Color.BLACK); // 设置边框颜色
heptagon.setStrokeWidth(2); // 设置边框宽度
double startX = centerX + radius * Math.cos(Math.toRadians(0));
double startY = centerY - radius * Math.sin(Math.toRadians(0)); // 注意Y轴的方向是向下的
double x1 = centerX + radius * Math.cos(Math.toRadians(7 * angleStep));
double y1 = centerY - radius * Math.sin(Math.toRadians(7 * angleStep)); // 注意Y轴的方向是向下的
x1 = x1 - 2*(x1-centerX)/3;
y1 = y1 - 2*(y1-centerY)/3;
heptagon.getElements().add(new MoveTo( x1,y1));
//圆点的集合
List<Circle> circles = new ArrayList<>();
List<Label> labels = new ArrayList<>();
// 添加剩余的顶点(线条到)
for (int i = 1; i <= 7; i++) {
double angle = i * angleStep;
double x = centerX + radius * Math.cos(Math.toRadians(angle));
double y = centerY - radius * Math.sin(Math.toRadians(angle)); // 注意Y轴的方向是向下的
if (i == 3) {
x = x - (x-centerX)/3;
y = y - (y-centerY)/3;
}
if (i == 7) {
x = x - 2*(x-centerX)/3;
y = y - 2*(y-centerY)/3;
}
heptagon.getElements().add(new LineTo(x, y));
Circle circle1 = new Circle();
circle1.setCenterX(x); // 设置圆心X坐标
circle1.setCenterY(y); // 设置圆心Y坐标
circle1.setRadius(5); // 设置半径
circle1.setFill(Color.BLUE); // 设置填充颜色
circle1.setStroke(Color.BLACK); // 设置边框颜色
circle1.setStrokeWidth(2); // 设置边框宽度
circles.add(circle1);
Label label = new Label(String.valueOf(i));
label.setLayoutX(x);
label.setLayoutY(y-30);
labels.add(label);
}
// 确保路径闭合(可选,但对于多边形来说通常是个好习惯)
// heptagon.getElements().add(new LineTo(startX, startY));
root.getChildren().add(heptagon);
// 将七边形添加到场景中
root.getChildren().addAll(circles);
root.getChildren().addAll(labels);
}
}
用javafx Path 类画折线图,通过定义起点 以及经过点 画出折线 与 画画类似,一笔笔的画出来,计算出下一个点的坐标位置即可完成。
如图