SVG Cairo goodness

I’ve been hacking on binding the libsvg-cairo library as an add-on to the existing cairo bindings. It’s actually quite a nice small API.

[img]

Gtk2Hs can already load SVG files, but only as fixed size bitmaps. With this API we get a proper vector method. Since the drawing is done via cairo in the Render monad we can apply any 2D transformation. These screenshots are of a simple svg viewer. It’s only 30 lines of code overall. The following snippet is what does the actual drawing.

win <- drawingAreaGetDrawWindow canvas
let (width, height) = sizeSVG svg
(width', height') <- drawingAreaGetSize canvas
renderWithDrawable win $ do
  scale (realToFrac width' / realToFrac width)
        (realToFrac height' / realToFrac height)
  renderSVG svg

You can see that we setup the scaling transformation before rendering the svg picture. We scale the image so that it fits the size of the canvas. So as we resize the window the image scales nicely.

[img]

3 Responses to “SVG Cairo goodness”

  1. squark Says:

    Hello,
    Could you give the entire code for this little SVG viewer?

  2. Duncan Says:

    Certainly. It’s included in the demo collection that is distributed with Gtk2Hs, or you can grab it from our dev repo:
    http://darcs.haskell.org/gtk2hs/demo/svg/SvgViewer.hs

  3. squark Says:

    Thank you :)