Pycairo

1.29.0 · active · verified Thu Apr 09

Pycairo is a Python module providing bindings for the cairo graphics library. It enables Python programs to create high-quality vector graphics that scale without loss of clarity and can be output in various formats like PNG, SVG, PDF, and PostScript. The library is actively maintained with regular releases, typically multiple per year, following semantic versioning since v1.11.0. It currently supports Python 3.10+ and PyPy3.

Warnings

Install

Imports

Quickstart

This quickstart code creates an ImageSurface and a Context object, then draws a Bezier curve with guide lines, and finally saves the output to a PNG file. This demonstrates basic surface and context creation, drawing commands, and outputting to a file.

import cairo
import math

WIDTH, HEIGHT = 256, 256

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

ctx.scale(WIDTH, HEIGHT)
ctx.set_line_width(0.04)

# Draw a curve
x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9
x2, y2, x3, y3 = 0.6, 0.1, 0.9, 0.5
ctx.move_to(x, y)
ctx.curve_to(x1, y1, x2, y2, x3, y3)
ctx.stroke()

# Draw guide lines
ctx.set_source_rgba(1, 0.2, 0.2, 0.6) # Red with transparency
ctx.set_line_width(0.02)
ctx.move_to(x, y)
ctx.line_to(x1, y1)
ctx.move_to(x2, y2)
ctx.line_to(x3, y3)
ctx.stroke()

surface.write_to_png("example.png")
print("Generated example.png")

view raw JSON →