I am trying to draw a rectangle around a text element using getBBox (), the code is pretty simple, create a document, add a text element, a boot document and add a rectangle. The problem is that getBBox returns some strange values, am I missing something?
DOMImplementation impl;
String svgNS;
SVGDocument doc;
Element svgRoot;
UserAgent userAgent;
DocumentLoader loader;
BridgeContext ctx;
GVTBuilder builder;
GraphicsNode rootGN;
...
impl = SVGDOMImplementation.getDOMImplementation();
svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
doc = (SVGDocument)impl.createDocument(svgNS, "svg", null);
svgRoot = doc.getDocumentElement();
svgRoot.setAttributeNS(svgNS, "width", "400");
svgRoot.setAttributeNS(svgNS, "height", "450");
Element txtElem = doc.createElementNS(svgNS, "text");
txtElem.setAttributeNS(svgNS, "x", "30");
txtElem.setAttributeNS(svgNS, "y", "50");
txtElem.setAttributeNS(svgNS, "style", "font-family:Arial;font-size:20;stroke:#000000;#fill:#00ff00;");
txtElem.setTextContent("sometext");
svgRoot.appendChild(txtElem);
userAgent = new UserAgentAdapter();
loader = new DocumentLoader(userAgent);
ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
builder = new GVTBuilder();
rootGN = builder.build(ctx, doc);
NodeList nodelist = doc.getElementsByTagName("text");
for (int i=0; i < nodelist.getLength(); i++) {
SVGOMTextElement textElem = (SVGOMTextElement)nodelist.item(i);
SVGRect bbox = textElem.getBBox();
Element rectangle = doc.createElementNS(svgNS, "rect");
rectangle.setAttributeNS(svgNS, "x", new Float(bbox.getX()).toString());
rectangle.setAttributeNS(svgNS, "y", new Float(bbox.getY()).toString());
rectangle.setAttributeNS(svgNS, "width", new Float(bbox.getWidth()).toString());
rectangle.setAttributeNS(svgNS, "height", new Float(bbox.getHeight()).toString());
rectangle.setAttributeNS(svgNS, "fill", "rgba(0,0,0,0)");
rectangle.setAttributeNS(svgNS, "stroke", "#ff0000");
rectangle.setAttributeNS(svgNS, "stroke-width", "1");
svgRoot.appendChild(rectangle);
}
this is the SVG document that I get, since you can see that the rectangle has different X and Y values (width and height are also incorrect).
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" contentScriptType="text/ecmascript" zoomAndPan="magnify" width="400" contentStyleType="text/css" preserveAspectRatio="xMidYMid meet" height="450" version="1.0">
<text x="30" style="font-family:Georgia;font-size:20;stroke:#000000;#fill:#00ff00;" y="50">sometext</text>
<rect x="0.65234375" fill="rgba(0,0,0,0)" width="55.621094" stroke-width="1" stroke="#ff0000" height="8.597656" y="8.425781"/>
</svg>