Posted on Jul 8, 2007

SVG Shape 2 Java2D Code

A couple weeks ago I needed to write some Java2D code to draw a water droplet. If you have ever tried coding bezier paths off the top of you head it is not the simplest of things and can be frustrating. So I ended up drawing it in Illustrator and saving as SVG. The next stage was hacking with some code I had from before to take the path and spit out Java2D code for the shape. I have been thinking since that I could cleanup the code when I get the time and make a little application for extracting path shapes from SVG and writing out the Java2D code for them. Well I finally got the time and here is what I came up with.

SvgShapeExtractor Screen Shot

Download:
SvgShapeExtractor.jar (Executable Jar)
SvgShapeExtractorSrc.zip (Src)

Hopefully you will find this useful next time you need to write some Java2D shape code.

5 Comments

  • I wrote a similar tool back a few months ago. It supports almost everything in SVG (not a single path) except texts.

  • [...] Shape 2 SVB is available from Jasper’s blog. [...]

  • Kiyut says:

    Another way to generate shape easily is to have function that return GeneralPath with parameter SVG path string

    public GeneralPath generatPath(String s) {
    // code to return GeneralPath, should be similar to above with slight modification
    }

    use case:
    String s = “M 167.0 197.0 C 177.0 169.0 177.0 169.0 177.0 169.0 C 191.0 143.0 191.0 143.0 191.0 143.0 C 215.0 117.0 215.0 117.0 215.0 117.0″;
    GeneralPath path = generatePath(s);
    // draw the path to output media

  • Thera says:

    I was looking on the internet for a way to translate svg’s paths to java2d. So I was happy to find this application. However, it seems something has been changed to the Java2d parameters, and your application’s output doesn’t work any more.

    I’ve tried to figure out what the exact changes were, but it seems my google-fu doesn’t work for me today.
    So my question is, what does the program exactly output?(Like, what were the parameters for curveTo back then) So I can adapt the parameters myself.

    Still awesome idea.

  • Guillaume says:

    Thera :
    I’ve had the same issue, which is actually due to a formatter in SvgPath.java.getJava2DCode() :

    DecimalFormat format = new DecimalFormat();
    format.setMaximumFractionDigits(2);

    I guess that depending on your Locale, the separator in a Decimal is “,”, so you end up with more “,” than expected, and thus with more points than expected.

    Since Jasper provides us with the source code, one can easily fix that. Though, it requires the use of IntelliJ Idea (http://www.jetbrains.com/idea/) so you can compile the UI (of which I am not very found of).

    Jasper :
    Wouldn’t it be cool to put the code on a GIT repository, so that the community can participate in that great idea ? Thanks for the program !