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

最佳答案

我找到了由用户templth开发的batik users forum的答案,我不敢相信,我只是在此处重新发布了解决方案,以便可以有更多的机会。

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;
    }
}


在蜡染布1.9上测试。此方法仅返回指定位置上的最顶层元素。解决方法是,删除该元素,然后再次调用nodeHitAt。

10-06 14:03