如何在Batik坐标处获取SVG节点

时间:2017-05-25 10:02:25

标签: java svg batik

我有一个SVG和点(例如(x,y)=(250,112))。 BATIK是否可以在给定点获取节点(DOM元素)?

1 个答案:

答案 0 :(得分:1)

我在batik users forum找到了用户templth开发的答案,我没有信任我只是在这里重新发布解决方案所以它可以有更多曝光。

public Element elementAtPosition(Document doc, Point2D point) {
    UserAgent userAgent = new UserAgentAdapter();
    DocumentLoader loader = new DocumentLoader(userAgent);
    BridgeContext context = new BridgeContext(userAgent, loader);
    context.setDynamicState(BridgeContext.DYNAMIC);
    GVTBuilder builder = new GVTBuilder();
    GraphicsNode rootGraphicsNode = builder.build(context, doc);

    // rootGraphicsNode can be offseted relative to coordinate system
    // that means calling this method on coordinates taken directly from the svg file might not work
    // check the bounds of rootGraphicsNode to determine where the elements actually are
    // System.out.println(rootGraphicsNode.getBounds());

    GraphicsNode graphicsNode = rootGraphicsNode.nodeHitAt(point);
    if (graphicsNode != null) {
        return context.getElement(graphicsNode);
    } else {
        // if graphicsNode is null there is no element at this position
        return null;
    }
}

在Batik 1.9上测试过。此方法仅返回指定位置的最顶层元素。作为一种解决方法,您可以删除元素并再次调用nodeHitAt。

相关问题