SoFunction
Updated on 2025-04-14

Python Cairo library usage tutorial and code case

1. Introduction to Cairo

Cairo is a 2D vector graphics library that supports a variety of output devices (such as PNG, PDF, SVG, and windowing systems). PyCairo is a Python binding of Cairo, allowing high-quality graphic drawing through Python code.

2. Install PyCairo

# Install via pip (note that the package name may be pycairo or cairo)pip install pycairo

3. Basic concepts and core categories

  1. Surface
    Represents the target media (such as memory, files, windows) of the drawing. Common types:

    • ImageSurface: Bitmap image (such as PNG)
    • PDFSurface: PDF file
    • SVGSurface: SVG vector
  2. Context (context)
    Controls the core objects of drawing operations and manages drawing status such as paths, colors, transformations, etc.

4. Basic drawing methods

Example 1: Drawing Simple Graphics (PNG)

import cairo

# 1. Create Surface and Contextwidth, height = 400, 300
surface = (.ARGB32, width, height)
ctx = (surface)

# 2. Set background colorctx.set_source_rgb(0.9, 0.9, 0.9)  # RGB range 0~1()  # Fill the entire surface
# 3. Draw a red rectanglectx.set_source_rgb(1, 0, 0)         # red(50, 50, 100, 80)      # (x, y, width, height)
()                          # Fill the shape
# 4. Draw a blue border circle(250, 150, 40, 0, 2 * 3.14159)  # (x, y, radius, start_angle, end_angle)
ctx.set_source_rgb(0, 0, 1)            # bluectx.set_line_width(3)                  # Line width()                           # Stroke path
# 5. Save as PNGsurface.write_to_png("basic_shapes.png")

Note:

  • set_source_rgb(): Set the drawing color (RGB value).
  • rectangle()andarc(): Define the path shape.
  • fill()andstroke(): Represents the fill path and draw path borders respectively.
  • write_to_png(): Save the result as a PNG file.

V. Advanced Features

1. Coordinate Transformation

# Examples of translation, rotation, and zoom()                  # Save the current status(200, 150)     # Move origin to (200,150)(0.25 * 3.14159)  # Rotate 45 degrees (radian system)(2, 2)             # Zoom 2x(-20, -20, 40, 40)  # Draw a squarectx.set_source_rgb(0, 1, 0)
()
()               # Restore the saved state

2. Gradient fill

# Linear Gradientlinear = (0, 0, 300, 300)
linear.add_color_stop_rgba(0, 1, 0, 0, 1)    # Starting point redlinear.add_color_stop_rgba(1, 0, 0, 1, 0.5)  # End point translucent bluectx.set_source(linear)
(50, 50, 200, 200)
()

3. Path operation and curve

# Draw Bezier curvesctx.move_to(50, 200)                # Starting pointctx.curve_to(100, 50, 200, 350, 350, 200)  # Control point 1, Control point 2, End pointctx.set_source_rgb(0.5, 0, 0.5)
ctx.set_line_width(4)
()

4. Text Rendering

# Set font and draw textctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
ctx.set_font_size(30)
ctx.move_to(50, 100)
ctx.set_source_rgb(0, 0, 0)
ctx.show_text("Hello Cairo!")  # Draw text

6. Comprehensive case: Drawing complex graphics

import cairo

# Initializationsurface = (.ARGB32, 600, 400)
ctx = (surface)
ctx.set_source_rgb(1, 1, 1)
()

# Draw a gradient backgroundgradient = (300, 200, 10, 300, 200, 300)
gradient.add_color_stop_rgba(0, 0.8, 0.8, 1, 1)
gradient.add_color_stop_rgba(1, 0.2, 0.2, 0.5, 1)
ctx.set_source(gradient)
(0, 0, 600, 400)
()

# Draw a rotating rectangle()
(300, 200)
for i in range(12):
    (3.14159 / 6)  # Rotate 30 degrees each time    ctx.set_source_rgba(0, 0.5, 0, 0.5)
    (-30, -30, 60, 60)
    ()
()

# Save the resultssurface.write_to_png("advanced_demo.png")

7. Key points to note

  1. Coordinate system: Origin(0,0)In the upper left corner, x grows to the right and y grows to the downward.
  2. Path operation: All paths must be passedfill()orstroke()It will take effect.
  3. State Stacksave()andrestore()Used to manage drawing state (such as color, transformation).

By combining basic methods and advanced features, Cairo enables complex vector graphics drawing. Recommended referenceCairo official documentationExplore more features in depth.

This is the article about the use of Python Cairo library and code cases. For more information about Python Cairo library usage, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!