JavaFX绘制流程图:如何实现带圆角的线段连接?
在JavaFX中绘制带圆角的流程图线段
要实现示例中的圆角转角线段,有两种常用方案,可根据需求选择:
方案一:精确控制圆角半径(推荐用于流程图)
使用Path类自定义路径,通过MoveTo、LineTo和ArcTo组合,手动在转角处添加圆弧过渡,能精准控制圆角大小:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.ArcTo; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class RoundedFlowLine extends Application { @Override public void start(Stage stage) { Pane root = new Pane(); Path roundedPath = new Path(); // 基础样式设置 roundedPath.setStroke(Color.BLACK); roundedPath.setStrokeWidth(2); roundedPath.setFill(Color.TRANSPARENT); // 自定义圆角半径 double cornerRadius = 10; // 构建路径:起点 → 水平右移 → 圆角下转 → 垂直下移 → 圆角右转 → 水平右移 roundedPath.getElements().add(new MoveTo(50, 50)); roundedPath.getElements().add(new LineTo(150 - cornerRadius, 50)); // 右上角圆角:从水平段终点过渡到垂直段起点 ArcTo arcRightDown = new ArcTo(); arcRightDown.setRadiusX(cornerRadius); arcRightDown.setRadiusY(cornerRadius); arcRightDown.setX(150); arcRightDown.setY(50 + cornerRadius); arcRightDown.setSweepFlag(true); // 顺时针绘制圆弧 roundedPath.getElements().add(arcRightDown); roundedPath.getElements().add(new LineTo(150, 150 - cornerRadius)); // 右下角圆角:从垂直段终点过渡到水平段起点 ArcTo arcDownRight = new ArcTo(); arcDownRight.setRadiusX(cornerRadius); arcDownRight.setRadiusY(cornerRadius); arcDownRight.setX(150 + cornerRadius); arcDownRight.setY(150); arcDownRight.setSweepFlag(true); roundedPath.getElements().add(arcDownRight); roundedPath.getElements().add(new LineTo(250, 150)); root.getChildren().add(roundedPath); Scene scene = new Scene(root, 300, 200); stage.setTitle("圆角流程图线段"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
代码说明
Path是JavaFX中最灵活的路径绘制类,支持任意复杂的线段组合。ArcTo的radiusX/Y直接控制圆角大小,sweepFlag确保圆弧方向符合转角需求(顺时针设为true)。- 每个转角处需要将直线段提前终止于圆角前的位置,再通过圆弧连接到下一段直线的起点,保证过渡平滑。
方案二:简单圆角过渡(随线段宽度自适应)
如果不需要精确控制圆角半径,仅需基础的圆角转角,可以使用Polyline并设置线段连接样式:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Polyline; import javafx.scene.shape.StrokeLineJoin; import javafx.stage.Stage; public class SimpleRoundedLine extends Application { @Override public void start(Stage stage) { Pane root = new Pane(); Polyline polyline = new Polyline(50,50, 150,50, 150,150, 250,150); polyline.setStroke(Color.BLACK); polyline.setStrokeWidth(2); polyline.setStrokeLineJoin(StrokeLineJoin.ROUND); // 转角圆角 polyline.setStrokeLineCap(StrokeLineCap.ROUND); // 线段端点圆角(可选) root.getChildren().add(polyline); Scene scene = new Scene(root, 300, 200); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
说明
StrokeLineJoin.ROUND会让线段连接处生成圆角,圆角大小与线段宽度成正比。- 这种方式代码更简洁,但无法独立控制圆角半径,适合对圆角精度要求不高的场景。
内容的提问来源于stack exchange,提问作者Lson
相关产品推荐
相关产品推荐

