cffi-based cairo bindings for Python
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
- breaking Changed `ImageSurface.get_data()` return type from `bytearray` to `memoryview`.
- gotcha The Cairo C library must be installed on your system.
- gotcha For file-based surfaces (e.g., PDFSurface, SVGSurface), `surface.finish()` is crucial to ensure all drawing operations are flushed and the file is properly closed.
- gotcha While API compatible, `cairocffi` does not provide a module named `cairo` directly. Code written for `pycairo` using `import cairo` will fail.
Install
-
pip install cairocffi
Imports
- cairo
import cairocffi as cairo
- ImageSurface
from cairocffi import ImageSurface
Quickstart
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()