Line Styles

Learn about the different line styles in Pycairo.

We'll cover the following...

Line caps

The line cap value affects how the ends of the lines are drawn. There are three options: butt, square, and round.

Here is the code that is used to draw these lines:

Press + to interact
import cairo
# Set up surface
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 400)
ctx = cairo.Context(surface)
ctx.set_source_rgb(0.8, 0.8, 0.8)
ctx.paint()
# Set line color and width
ctx.set_source_rgb(0, 0, 0)
ctx.set_line_width(20)
# Butt Cap
ctx.move_to(100, 80)
ctx.line_to(500, 80)
ctx.set_line_cap(cairo.LINE_CAP_BUTT)
ctx.stroke()
# Square Cap
ctx.move_to(100, 200)
ctx.line_to(500, 200)
ctx.set_line_cap(cairo.LINE_CAP_SQUARE)
ctx.stroke()
# Round Cap
ctx.move_to(100, 320)
ctx.line_to(500, 320)
ctx.set_line_cap(cairo.LINE_CAP_ROUND)
ctx.stroke()

The lines are drawn in the normal way, except that we make an extra call to the set_line_cap function to set the line cap style for each line. For demonstration purposes, red dots have been added to mark the exact positions of the points passed into the line_to and move_to functions, in the image below.

  • The first option is LINE_CAP_BUTT. This is the default, if we don’t call the set_line_cap function at all. The line starts and ends exactly on the points specified and the ends are squared off. This is useful if we want to ensure that our lines are exactly the right length.
  • The second option is LINE_CAP_SQUARE. In this case, the line ends are squared off, but they extend slightly beyond the exact points. In fact, they extend by exactly half of the line width.
  • The last option is LINE_CAP_ROUND. In this case, the line ends are semi-circles that extend beyond the exact points. The radius of the semi-circle is exactly half of the line width.

The choice is largely dependent on the visual effect we wish to achieve. The line cap style also affects the line dashes. We might also prefer to match the line cap style with the line join style.

Here is how the ...