Fill and stroke

Code: examples/cairo-fill-and-stroke.py on github

Here are 3 rectangles. One is filled in green, one is stroked (outlined) is red, the other is filled and stroked (in yellow and blue):

Here is the code:

import cairo
 
width = 500
height = 500
 
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
 
#Fill a rectangle
ctx.rectangle(100, 100, 200, 100)
ctx.set_source_rgb(0, 1, 0)
ctx.fill()
 
#Stroke a rectangle
ctx.rectangle(100, 250, 200, 100)
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(5)
ctx.stroke()
 
#Fill and stroke a rectangle
ctx.rectangle(350, 150, 100, 250)
ctx.set_source_rgb(1, 1, 0)
ctx.fill_preserve()
ctx.set_source_rgb(0, 0, 1)
ctx.set_line_width(10)
ctx.stroke()
 
surface.write_to_png("cairo_fill_and_stroke.png")

Filling a shape

In this code, we create a rectangle shape. The rectangle function takes 4 parameters: the x and y position of the top left of the rectangle, the width and the height.

Then we set the fill to an RGB colour. set_source_rgb takes 3 parameters, the R, G and B components (value 0.0 to 1.0).

Finally we fill the shape with the chosen colour.

#Fill a rectangle
ctx.rectangle(100, 100, 200, 100)
ctx.set_source_rgb(0, 1, 0)
ctx.fill()

Outlining a shape

Again, we create a rectangle shape and set an RGB colour.

This time we also need to set the thickness of the line using set_line_width.

We use the stroke function to outline the shape.

#Stroke a rectangle
ctx.rectangle(100, 250, 200, 100)
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(5)
ctx.stroke()

Filling and outlining a shape

To fill and outline the rectangle, we combine both operations from the previous examples.

There is one small difference. We need to use fill_preserve() to fill the rectangle. This is because the normal fill() function destroys the rectangle after filling it. We want to preserve the rectangle so we can use it with the stroke() function.

#Fill and stroke a rectangle
ctx.rectangle(350, 150, 100, 250)
ctx.set_source_rgb(1, 1, 0)
ctx.fill_preserve()
ctx.set_source_rgb(0, 0, 1)
ctx.set_line_width(10)
ctx.stroke()