Thursday, June 5, 2014

Java & Batik: How to transform arbitrary SVG elements!

Batik is a powerful library for handling SVG documents. I recently wrote an answer on StackOverflow.com on how to display SVG document in a JavaFX ImageView component. Apart from that, I also needed a means to transform (i.e. rotate, scale, translate) an arbitrary SVG element.

Translating a rectangle is fairly easy: Get its x and y attributes using getAttribute(null, localName), modify them and reassign them back using setAttributeNS(null, qualifiedName, value).
The tricky bit comes into play if you also want to rotate or scale the rectangle. The solution is to use SVG's transform attribute, which combines translating, scaling, rotating and skewing effects in a transformation matrix. This option also allows one to modify arbitrary SVG elements (incl. groups)!

I've come up with two usable utility classes, which you can freely use.

I would like to sincerely thank:

tl;dr: Code!

Full source code at: GitHub Gist: Transformation of arbitrary SVG elements with Batik

Usage Example


AffineTransformUtils.java


SVGUtils.java