如何使用ELK(Eclipse Layout Kernel)将节点置于同一层级
解决ELK Layered布局中指定节点同层级的问题
我之前在用ELK的layered布局做图时也碰到过一模一样的需求,要强制让特定节点处于同一层级,其实用ELK自带的节点层级约束配置就能搞定,核心是用到elk.layered.constraints.nodeLayers这个布局选项。
具体操作步骤:
- 在根节点的
layoutOptions里新增elk.layered.constraints.nodeLayers配置项,它是一个数组,每一个元素对应一组要放在同一层级的节点。 - 每组节点通过
nodes数组指定对应的节点ID,ELK会自动把这些节点安排到同一层级,同时尽量保证整体布局的合理性。
修改后的完整JSON配置示例:
{ "children": [ { "id": "42926", "x": 0, "y": 0, "width": 200, "height": 216 }, { "id": "42930", "x": 0, "y": 0, "width": 200, "height": 48 }, { "id": "42942", "x": 0, "y": 0, "width": 200, "height": 172 }, { "id": "42920", "x": 0, "y": 0, "width": 200, "height": 68 }, { "id": "42945", "x": 0, "y": 0, "width": 200, "height": 48 }, { "id": "42958", "x": 0, "y": 0, "width": 200, "height": 71 }, { "id": "43735", "x": 0, "y": 0, "width": 200, "height": 48 }, { "id": "43719", "x": 0, "y": 0, "width": 200, "height": 164 }, { "id": "43720", "x": 0, "y": 0, "width": 200, "height": 48 }, { "id": "43739", "x": 0, "y": 0, "width": 480, "height": 307 }, { "id": "43742", "x": 0, "y": 0, "width": 200, "height": 68 }, { "id": "43744", "x": 0, "y": 0, "width": 200, "height": 51 }, { "id": "42975", "x": 0, "y": 0, "width": 200, "height": 68 }, { "id": "43015", "x": 0, "y": 0, "width": 200, "height": 88 }, { "id": "43013", "x": 0, "y": 0, "width": 200, "height": 68 } ], "edges": [ { "id": "42920_42926", "source": "42920", "target": "42926" }, { "id": "42920_42942", "source": "42920", "target": "42942" }, { "id": "42920_42958", "source": "42920", "target": "42958" }, { "id": "42920_43719", "source": "42920", "target": "43719" }, { "id": "42926_42930", "source": "42926", "target": "42930" }, { "id": "42942_42945", "source": "42942", "target": "42945" }, { "id": "42958_43735", "source": "42958", "target": "43735" }, { "id": "43719_43720", "source": "43719", "target": "43720" }, { "id": "43739_43742", "source": "43739", "target": "43742" }, { "id": "43739_43013", "source": "43739", "target": "43013" }, { "id": "43742_43744", "source": "43742", "target": "43744" }, { "id": "43744_42926", "source": "43744", "target": "42926" }, { "id": "43744_42942", "source": "43744", "target": "42942" }, { "id": "43744_42958", "source": "43744", "target": "42958" }, { "id": "43744_43719", "source": "43744", "target": "43719" }, { "id": "42975_43739", "source": "42975", "target": "43739" }, { "id": "43013_43015", "source": "43013", "target": "43015" } ], "id": "root", "layoutOptions": { "elk.algorithm": "layered", "elk.direction": "DOWN", "elk.hierarchyHandling": "INCLUDE_CHILDREN", "elk.layered.spacing.edgeNodeBetweenLayers": 40, "elk.layered.nodePlacement.bk.fixedAlignment": "BALANCED", "elk.layered.constraints.nodeLayers": [ { "nodes": ["42926", "42942"] // 替换为你需要设置同层级的红色节点ID } ] } }
额外提示:
如果遇到布局约束冲突(比如节点的边连接关系导致层级安排矛盾),可以给目标节点单独添加elk.layered.constraints.nodeLayerPriority配置,设置一个较高的数值(比如100),提升层级约束的优先级,确保ELK优先满足节点同层级的要求。
内容的提问来源于stack exchange,提问作者omygoodness
相关产品推荐
相关产品推荐

