how do I change the alpha channel along a path in cairo?

19 Views Asked by At

In an application using gtk3, I use cairo to do some drawing. What I would like to do is increase the transparency along the path. The path can have any shape.

In very simplified terms, I have something like this:

#include <cairo.h>

int main(int argc, char *argv[]) {
    cairo_surface_t *surface =
        cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 200, 200);
    cairo_t *cr = cairo_create(surface);

    cairo_set_source_rgb(cr, .1, .1, .1);
    cairo_paint(cr);

    cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
    cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
    cairo_set_line_width(cr, 20.0);

    cairo_set_source_rgba(cr, 1.0, 1.0, 0.0, 0.6);
    int x = 10;
    int y = 10;

    cairo_move_to(cr, x, y);
    x += 150;
    cairo_line_to(cr, x, y);
    cairo_stroke(cr);

    cairo_set_source_rgba(cr, 1.0, 1.0, 0.0, 0.4);
    cairo_line_to(cr, x, y);
    x -= 50;
    y += 150;
    cairo_line_to(cr, x, y);
    cairo_stroke(cr);

    cairo_destroy(cr);
    cairo_surface_write_to_png(surface, "mwe.png");
    cairo_surface_destroy(surface);
    return 0;
}

When I draw the sections in pieces, each with a different alpha value, start and end overlap and -- not surprisingly -- I get this result:

enter image description here

Now my question is whether there is a way to "fade" the line along the path.

I thought of using a mask to restrict the drawing to where the last segment wasn't already (cairo_clip?), but don't know how to do that with a non-closed line.

But maybe there is an easier way to achieve this altogether ?

0

There are 0 best solutions below