Masking

Learn about the concept of masking in Pycairo.

What is masking?

Masking paints a pattern through a mask, which can be another pattern or surface, such as an image surface.

Masking allows us to use any pattern as a transparency mask on any other pattern.

As we discussed previously, a pattern can be a solid color, gradient, image, or surface with vector content.

There are three stages to this.

First, we create the mask:

radial=cairo.RadialGradient(200, 200, 100, 200, 200, 200)
radial.add_color_stop_rgba(0, 0, 0, 0, 1)
radial.add_color_stop_rgba(1, 0, 0, 0, 0)

The pattern radial is a radial gradient. The center is (200, 200), the inner circle has a radius of 100, and the outer circle has a radius of 200.

The stops use add_color_stop_rgba to create stops that have a transparency component. The first stop is black, with an alpha value of 1, which makes it fully opaque. The outer circle is also black, with an alpha value of 0, which makes it fully transparent.

The effect of this is to have a black central area, and an outer ring where the black fades out (it becomes more and more transparent). Beyond the outer circle, the gradient is fully transparent, so the white background shows through.

Next, we create the tiger image:

image = cairo.ImageSurface.create_from_png('tiger.png')
ctx.set_source_surface(image)

We create an ImageSurface from the PNG file, and set that surface as a current source with the use of the set_source_surface function.

Now, we can create the output:

ctx.mask(radial)

We take the current source, the tiger ImageSurface, and apply it with the radial mask. This, effectively, applies the mask alpha channel to the image, which creates an image that is fully opaque in the center but fades out at the edges.

Get hands-on with 1400+ tech skills courses.