Search code examples
c++ccairogtkmm

DrawingArea: fill area outside a region


I have followed this gtkmm tutorial on how to draw shapes and fill them with colors (e.g. A red disc on a transparent background). I was also able, from this example, to derive another example with a red disc on a blue background.

However, what I would really need is a transparent disc with a blue background that fills everything minus the disc area, which should stay transparent.

So with cairo, the usual workflow is:

  1. Create a surface
  2. Draw a shape (e.g. draw a circle)
  3. Fill the circle, so that it becomes a disc.

I would need some workflow that achieves something like this instead:

  1. Create a surface
  2. Draw a shape (e.g. draw a circle)
  3. Fill the area outside the circle, so that I have a colored background with a transparent "hole" in the middle.

I have done some research on this on the web but all examples seem to assume that we want to fill the inner region of a shape (which I must admit is more typical).

How could I do this?

P.S. I have added the C tag because I don't mind if you prefer to use C (or even Python).


Solution

  • Draw your circle and draw a rectangle containing all the visible area. Set the cairo fill rule to even/odd. Fill. Done.

    cairo_save(cr); // Save the state
    cairo_arc(cr, 42, 42, 21, 0, 2*M_PI); // Draw circle
    cairo_rectangle(cr, 0, 0, width, height); // Rectangle containing everything
    cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
    cairo_fill(cr);
    cairo_restore(cr); // Restore default fill rule (optional; pairs with save above)