Search code examples
graphics2dcairo

Use generated image as pattern inside cairo graphics


I've gone through the cairo graphics examples using pattern.

pattern = cairo_pattern_create_for_surface (image);
cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT);

Now instead of "image" I have a surface with a sequence of :-

cairo_move_to(cr, xc[0], yc[0]);
    for (int i = 0; i < xc.size(); i++)
        cairo_line_to(cr, xc[i], yc[i]);

How do I use this generated cairo surface and use it as input for the pattern ? It does not work if I simply use pattern = cairo_pattern_create_for_surface (surface); where surface has the cairo_t cr.


Solution

  • It does not work if I simply use pattern = cairo_pattern_create_for_surface (surface); where surface has the cairo_t cr.

    Yes, it does.

    The following code draws a cross to a 10x10 surface and then fill a 20x20 surface with this.

    enter image description here

    #include <cairo.h>
    
    int main()
    {
        cairo_surface_t *pattern_surface = cairo_image_surface_create(
                CAIRO_FORMAT_ARGB32, 10, 10);
        cairo_surface_t *result_surface = cairo_image_surface_create(
                CAIRO_FORMAT_ARGB32, 20, 20);
        cairo_t *cr;
        cairo_pattern_t *pattern;
    
        cr = cairo_create(pattern_surface);
        cairo_move_to(cr, 0, 0);
        cairo_line_to(cr, 10, 10);
        cairo_move_to(cr, 10, 0);
        cairo_line_to(cr, 0, 10);
        cairo_stroke(cr);
        cairo_destroy(cr);
    
        pattern = cairo_pattern_create_for_surface(pattern_surface);
        cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT);
    
        cr = cairo_create(result_surface);
        cairo_set_source(cr, pattern);
        cairo_paint(cr);
        cairo_destroy(cr);
    
        cairo_surface_write_to_png(result_surface, "out.png");
    
        cairo_surface_destroy(pattern_surface);
        cairo_surface_destroy(result_surface);
        cairo_pattern_destroy(pattern);
        return 0;
    }