xmlgraphics-batik-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From George Armhold <armh...@cs.rutgers.edu>
Subject getting bounds of SVG in JSVGComponent- example code
Date Thu, 04 Sep 2003 14:22:57 GMT
Hi all,

Just wanted to share a bit of code I put together for determining the
bounds of the SVG document when displayed in the JSVGComponent.  We
had a need to detect "out of bounds" conditions for MouseEvents and I
was a bit stumped about how to get the bounds of the SVG doc in the
component.  I found that I could deduce the bounds via the viewBox
attribute if present in the document.  You can drop this method into
anything that extends JSVGComponent to make it work.  Perhaps there is
a more standard way to get this info, but I couldn't find it in the
API docs.  Anyway I hope someone finds it useful.

    * Initialize the shape of the viewBox- this is the area (in AWT
    * coords) in the JComponent where the SVG is visible.  If no
    * viewBox is available we try to make this function fail
    * gracefully- no crashes.
   public Shape getViewBoxShape() {
     Document doc = getSVGDocument();
     if (doc == null) return null;

     Element root = doc.getDocumentElement();
     String viewBox = root.getAttribute("viewBox");

     if (viewBox == null) return null;

     // break viewBox string up into its 4 numbers
     // example: viewBox="0 0 25400 19100"

     String[] nums = viewBox.split("\\s+");
     if (nums.length != 4) return null; // fail gracefully!

     float x = Float.parseFloat(nums[0]);
     float y = Float.parseFloat(nums[1]);
     float width = Float.parseFloat(nums[2]);
     float height = Float.parseFloat(nums[3]);

     // construct a rectangle that describes the viewBox
     Rectangle2D rect = new Rectangle2D.Float(x, y, width, height);

     // locate the viewBox in AWT coordinate space of this JComponent
     AffineTransform aft = getViewBoxTransform();
     return aft.createTransformedShape(rect);

To unsubscribe, e-mail: batik-users-unsubscribe@xml.apache.org
For additional commands, e-mail: batik-users-help@xml.apache.org

View raw message