Search code examples
svgbatik

Get bounding box of svg element?


I want to know the bounding box of an svg element. Taken from the project's examples:

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

Now I try finding the bounding box:

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

What's the right way to query an element's bounding box?


Solution

  • This is cobbled together from a few different sources:

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

    that'll give you the bounds.