获取svg元素的边界框?

时间:2015-02-16 02:27:48

标签: svg batik

我想知道svg元素的边界框。摘自项目的例子:

DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document doc = impl.createDocument(svgNS, "svg", null);
Element svgRoot = doc.getDocumentElement();

Element rectangle = doc.createElementNS(svgNS, "rect");
rectangle.setAttributeNS(null, "x", "10");
rectangle.setAttributeNS(null, "y", "20");
rectangle.setAttributeNS(null, "width", "100");
rectangle.setAttributeNS(null, "height", "50");
rectangle.setAttributeNS(null, "fill", "red");

svgRoot.appendChild(rectangle);

现在我尝试找到边界框:

SVGOMElement svgelt = (SVGOMElement)rectangle;
SVGRect rc = SVGLocatableSupport.getBBox(svgelt); // rc == null

查询元素边界框的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

这是从几个不同来源拼凑而成的:

Document doc = loadYerSvgDoc();
BridgeContext ctx = new BridgeContext(new UserAgentAdapter());
GraphicsNode gvtRoot = builder.build(ctx, doc);
Rectangle2D rc = gvtRoot.getSensitiveBounds();

那将为你提供界限。