2012-08-28 14 views
5

Estoy tratando de dibujar un rectángulo alrededor de un elemento de texto usando getBox(), el código es bastante sencillo, crea documento, añade elemento de texto, documento de inicio y agrega rectángulo. El problema es que getBBox está devolviendo algunos valores extraños, ¿me falta algo?Valores erróneos del cuadro delimitador para elemento de texto con Batik

DOMImplementation impl; 
String svgNS; 
SVGDocument doc; 
Element svgRoot; 

UserAgent userAgent; 
DocumentLoader loader; 
BridgeContext ctx; 
GVTBuilder builder; 
GraphicsNode rootGN; 

... 

// get a DOM and create a document 
impl = SVGDOMImplementation.getDOMImplementation(); 
svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; 
doc = (SVGDocument)impl.createDocument(svgNS, "svg", null); 

// Get (the 'svg' element). 
svgRoot = doc.getDocumentElement(); 

// Set the width and height attributes on the root 'svg' element. 
svgRoot.setAttributeNS(svgNS, "width", "400"); 
svgRoot.setAttributeNS(svgNS, "height", "450"); 

// Add a text element 
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); 

// boot the document 
userAgent = new UserAgentAdapter(); 
loader = new DocumentLoader(userAgent); 
ctx = new BridgeContext(userAgent, loader); 
ctx.setDynamicState(BridgeContext.DYNAMIC); 
builder = new GVTBuilder(); 
rootGN = builder.build(ctx, doc); 

// add a bounding box to text elements 
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); 
} 

Este es el documento SVG que estoy recibiendo, como se puede ver el rectángulo tiene diferentes valores de Y (anchura y la altura también se equivocan) X e.

<?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> 
+0

¿Podría también publicar el código que agrega el rectángulo? –

+0

el código de agregación de rectángulo está dentro del bucle for, justo después del inicio del documento. No estoy seguro si esta es la manera correcta de hacerlo. –

+0

No importa, no me desplacé lo suficiente para ver el ciclo for ... –

Respuesta

4

El problema viene del hecho de que debe utilizar en lugar de setAttributesetAttributeNS. Las coordenadas x y y especificadas se ignoran porque no son los atributos x y y que Batik espera en el espacio de nombres predeterminado, parecen ser reconocidos como otros atributos desconocidos. Sólo tiene que utilizar esto:

txtElem.setAttribute("x", "30"); 
txtElem.setAttribute("y", "50"); 
txtElem.setAttribute("style", "font-family:Arial;font-size:20;stroke:#000000;fill:#00ff00;"); 
4

Prueba esto:

rectangle.setAttributeNS(null, 

y dejar svgNS sólo en createElementNS.

+1

No sé por qué esta respuesta recibió un voto negativo. 'setAttributeNS (null, ...)' incluso se declara como el método preferible (en lugar de 'setAttribute (...)') en las preguntas frecuentes oficiales de Batik: http://xmlgraphics.apache.org/batik/faq.html (vea la pregunta 3.4: "Cuando creo nuevos elementos SVG o modifico algunos atributos SVG a través de la API DOM, desde ECMAScript, no ocurre nada, los cambios no se representan. ¿Por qué no?") – ComFreek

Cuestiones relacionadas