Search code examples
rubygtk3cairo

Clear the current path in Cairo


In some Ruby code which uses Cairo, I need to draw a number of fills over a single path. This is part of a graphics application, where multiple fills may be stacked on top of each other using different blend modes.

Each fill is drawn using fill_preserve to preserve the path so that the next fill can occur over the same path without retracing it. This is done somewhat like so:

rectangle_data.each do |rectangle_datum|
    context.rectangle(*rectangle_datum.rectangle)
    fill_data.each do |fill_datum|
        context.set_source_rgba(*fill_datum.color)
        context.fill_preserve
    end
end

The problem is that this leaves the path even after all fills have taken place, which means that individual shapes are just drawn as one huge filled shape.

To solve this, I'd simply need to clear the current path manually, but I can't figure out how to do this. I've had a look through the documentation for Cairo::Context through Google Translate but I can't find it. (The docs are in Japanese!)

How can I manually clear a Cairo context's current path?


Solution

  • I had a look over Cairo::Context#methods and found #new_path, which does just what I'm after. So you can do:

    rectangle_data.each do |rectangle_datum|
        context.rectangle(*rectangle_datum.rectangle)
        fill_data.each do |fill_datum|
            context.set_source_rgba(*fill_datum.color)
            context.fill_preserve
        end
        context.new_path
    end