More on LinearGradient
In this lesson, we'll dive a bit deeper into `LinearGradient` in Pycairo.
We'll cover the following...
Adding more steps
Sometimes, we might want a gradient that doesn’t just transition from one color to another. We might want the gradient to move through multiple colors. This can be done using extra stops.
For one stop, we will use the following function once:
pattern.add_color_stop_rgb(position, r, g, b)
Now, we will run this function as many times as we want to add stops.
Here is an example of this:
Press + to interact
import cairoimport math# Set up surfacesurface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 600)ctx = cairo.Context(surface)ctx.set_source_rgb(1, 1, 1)ctx.paint()# Define gradientpattern = cairo.LinearGradient(200, 100, 200, 300)pattern.add_color_stop_rgb(0, 1, 0.5, 0.5)pattern.add_color_stop_rgb(0.5, 0, 1, 0)pattern.add_color_stop_rgb(0.75, 1, 1, 0)pattern.add_color_stop_rgb(1, 0.5, 0.5, 1)ctx.set_source(pattern)# Draw Circlectx.arc(450, 200, 100, 0, math.pi*2)ctx.fill()# Draw rectanglectx.rectangle(0, 50, 300, 300)ctx.set_source(pattern)ctx.fill()
Solid colors
Sometimes, we might want an area of solid color in our gradient. Here is an example of this:
Press + to interact
import cairoimport math# Set up surfacesurface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 600)ctx = cairo.Context(surface)ctx.set_source_rgb(1, 1, 1)ctx.paint()# Define gradientpattern = cairo.LinearGradient(200, 100, 200, 300)pattern.add_color_stop_rgb(0, 1, 1, 1)pattern.add_color_stop_rgb(0.25, 0.5, 0.5, 1)pattern.add_color_stop_rgb(0.75, 0.5, 0.5, 1)pattern.add_color_stop_rgb(1, 1, 1, 1)ctx.set_source(pattern)# Draw circlectx.arc(450, 200, 100, 0, math.pi*2)ctx.fill()# Draw rectanglectx.rectangle(0, 50, 300, 300)ctx.set_source(pattern)ctx.fill_preserve()ctx.set_source_rgb(0, 0, 0)ctx.set_line_width(1)ctx.stroke()
This gradient transitions from white to blue. There is a constant band of blue in the middle, which eventually fades back to white. ...