Groovy simple SVG Builder

As a little sidetrack from the work I’m doing at Pattern Design (a platform for repeatable vector patterns) I tried to programmatically create some SVG graphics myself – which is really easy with Groovy (like pretty much everything in Groovy 🙂 )

One of the more or less beautiful patterns is available on Pattern Design – Vertical Confetti Wave

Basically it wraps MarkupBuilder and provides some additional help. So, with some lines of code, you can start creating some fancy SVG imagery like this:


SVGBuilder.createSvg(new File("d:\\test.svg")) {
    300.times {
        // create a colorful dot at a random position
        circle(cx:Math.random() * width, cy:Math.random() * height,r:Math.min(width,height) / 50,fill:functions.hsbColor(Math.random()))
    }
}

Together with the SVGBuilder which provides the groundwork


import groovy.xml.MarkupBuilder
class SVGBuilder {
    static createSvg(File outputFile, Closure content) {
        def writer = new StringWriter()
        def markupBuilder = new MarkupBuilder(writer)
        def width = 1000
        def height = 1000
        def binding = new Binding()
        binding.setVariable('width', width)
        binding.setVariable('height', height)
        binding.setVariable('markupBuilder', markupBuilder) //provide the markupBuilder in case it's needed for advanced stuff
        binding.setVariable('functions', [hsbColor: hsbColor])
        content.setBinding(binding)
        content.setDelegate(markupBuilder)
        writer << '<?xml version="1.0" encoding="UTF-8" ?>'
        markupBuilder.svg(width:height,height:height, xmlns:'http://www.w3.org/2000/svg', 'xmlns:xlink':'http://www.w3.org/1999/xlink', version:'1.1') {
            content()
        }
        outputFile.withWriter {
            it << writer.toString()
        }
    }
    static def hsbColor = { hue, saturation = 1.0f, brightness = 1.0f ->
        def color = java.awt.Color.getHSBColor(hue as float, saturation as float, brightness as float)
        return "rgb(${color.red},${color.green},${color.blue})"
    }
}


there’s a nice image you can use for your mother-in-law’s birthday invitation card.

This entry was posted in Software. Bookmark the permalink.