cffi-based cairo bindings for Python

1.7.1 · active · verified Thu Apr 09

cairocffi provides Python bindings for the Cairo 2D graphics library, built using CFFI. It aims for API compatibility with Pycairo, allowing Python developers to leverage Cairo's powerful graphics capabilities with a more modern CFFI-based backend. The current version is 1.7.1, with releases occurring infrequently, often driven by new Cairo versions or minor bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an image surface, draw text onto it, and save the result as a PNG file. It highlights the typical import pattern and basic drawing operations using the Cairo API.

import cairocffi as cairo
import os

# Create an image surface (200x100 pixels, ARGB32 format)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 100)
ctx = cairo.Context(surface)

# Draw a light gray background
ctx.set_source_rgb(0.8, 0.8, 0.8) # R, G, B values (0.0-1.0)
ctx.paint()

# Set text color, font, and size
ctx.set_source_rgb(0, 0, 0) # Black
ctx.select_font_face('Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
ctx.set_font_size(24)

# Move to position and show text
ctx.move_to(10, 60) # x, y coordinates
ctx.show_text("Hello, cairocffi!")

# Define output path
output_filename = "hello_cairocffi.png"

# Write the surface content to a PNG file
surface.write_to_png(output_filename)
print(f"Generated {output_filename}")

# Clean up (optional for ImageSurface, but good practice for other surfaces like PDF/SVG)
surface.finish()

view raw JSON →