cppfw / svgren

:camera: SVG rendering library in C++
MIT License
206 stars 41 forks source link

Render with Cairo #41

Closed smags13 closed 6 years ago

smags13 commented 6 years ago

I'm new to svgren and cairo, following the basic tutorial.

After obtaining std::vector<uint32> by calling svgren::render(...), what should I do next with cairo to render the resulting data with a given cairo_surface_t *?

igagis commented 6 years ago

Basically, that std::vector<uint32> is the pixel data of your raster image. so, you need to draw that raster image with cairo.

To do that, you need to create a cairo image surface and the use it as source and draw with cairo_paint. The code would look something like that:

//Let's say you have the following variables assigned correct values
cairo_t *cr; //your cairo rendering context
std::vector<std::uint32_t> pixels; //pixel data you got from svgren::render(...)
unsigned imWidth, imHeight; //raster image width and height, obtained from svgren::render(...)

//Then draw the raster image to cairo context

//create image surface and initialize it with our pixel data
cairo_surface_t *imageSurface = cairo_image_surface_create_for_data(
        reinterpret_cast<unsigned char*>(&*pixels.begin()), //pointer to pixel data
        CAIRO_FORMAT_ARGB32, //data format is ARGB
        imWidth,
        imHeight,
        imWidth * sizeof(std::uint32_t) //stride
    );

//set the new image surface as source, dstX and dstY is where you want to draw the image
cairo_set_source_surface(cr, imageSurface, dstX, dstY);

//do the actual paint with current source
cairo_paint(cr);

//remove the surface if we don't need it anymore
cairo_surface_destroy(imageSurface);

I haven't tested the code, but it should give you the basic idea.

smags13 commented 6 years ago

Thank you @igagis for the code sample!

igagis commented 6 years ago

Hope it helps :)