Skip to content

Generate a gradient using Cairo in Python

#!/usr/bin/env python
# [SNIPPET_NAME: Gradient]
# [SNIPPET_CATEGORIES: Cairo]
# [SNIPPET_DESCRIPTION: Generate a gradient]
# [SNIPPET_DOCS: http://www.tortall.net/mu/wiki/CairoTutorial]
# [SNIPPET_LICENSE: MPL]

import math
import cairo
import os

WIDTH, HEIGHT  = 256, 256

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)

ctx.scale (WIDTH/1.0, HEIGHT/1.0)

pat = cairo.LinearGradient (0.0, 0.0, 0.0, 1.0)
pat.add_color_stop_rgba (1, 0, 0, 0, 1)
pat.add_color_stop_rgba (0, 1, 1, 1, 1)

ctx.rectangle (0,0,1,1)
ctx.set_source (pat)
ctx.fill ()

pat = cairo.RadialGradient (0.45, 0.4, 0.1,
                            0.4,  0.4, 0.5)
pat.add_color_stop_rgba (0, 1, 1, 1, 1)
pat.add_color_stop_rgba (1, 0, 0, 0, 1)

ctx.set_source (pat)
ctx.arc (0.5, 0.5, 0.3, 0, 2 * math.pi)
ctx.fill ()

# the output is written to your home directory
surface.write_to_png(os.path.expanduser("~") + '/gradient.png')
#surface.write_to_png(10)

Source

See also  Generate a spiral using Cairo in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.