Search code examples
c++svgpngcairo

What is the best way to load SVG as Cairo image surface?


I have a simple C++ program based on libCairo that is intended to draw some images (e.g. put one image onto another, write some text, and so on). I need to load some SVG files (to avoid scaling artifacts) and then draw them onto a surface that was loaded from PNG.

I have a wrapper class that contains a cairo_t context, and allows to get a surface from that context:

cairo_surface_t *CairoImage::getSurface() {
    return cairo_get_target(context);
}

I load SVG files currently like that:

CairoImage::CairoImage(const char *path, double width, double height) {
    auto surface = cairo_svg_surface_create(path, width, height);
    context = cairo_create(surface);
}

And this is how I'm drawing an image onto another:

    cairo_set_source_surface(context, image.getSurface(), 0, 0);
    cairo_rectangle(context, x, y, image.getWidth(), image.getHeight());
    cairo_clip(context);
    cairo_paint(context);
    cairo_reset_clip(context);

But it does not work (it just doesn't draw anything). How can this be solved?


Solution

  • Cairo can write SVG files, but it cannot read them.

    You need something like librsvg to load SVG files. I just tried to get Google to give me a short librsvg example, but did not find one.