ccairo

Cairo clip region existing of multiple rectangles?


I need a clip region that exists of a several (possibly overlapping) rectangles, but can't figure out how to create one with cairo.

Since there is a

cairo_rectangle_list_t *
cairo_copy_clip_rectangle_list (cairo_t *cr);

I assumed that the clip region CAN exist of more than one rectangle (if not, then this wouldn't return a list of rectangles...)

Moreover, cairo_rectangle_list_t exists - surely I can create a list of rectangles myself then... and create the clip region from that?

But how?


Solution

  • Just create a path that consists of several rectangles and clip with it. Here is an example with two overlapping rectangles, but it works just as well with more.

    Result of the following C program

    #include <cairo.h>
    
    int main() {
        cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 100, 100);
        cairo_t *cr = cairo_create(s);
    
        cairo_set_source_rgb(cr, 1, 1, 1);
    
        cairo_rectangle(cr, 10, 10, 50, 50);
        cairo_rectangle(cr, 40, 40, 50, 50);
        cairo_clip(cr);
        cairo_paint(cr);
    
        cairo_surface_write_to_png(s, "out.png");
        cairo_destroy(cr);
        cairo_surface_destroy(s);
        return 0;
    }