### Install xcffib and cairocffi Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Install xcffib first, then cairocffi, to enable XCB support. ```bash pip install xcffib pip install cairocffi ``` -------------------------------- ### Create and Draw on an Image Surface Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Demonstrates creating an image surface, setting a background color, applying text with transformations, and saving the output as a PNG file. Requires cairoffi to be installed. ```python surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200) context = cairo.Context(surface) with context: context.set_source_rgb(1, 1, 1) # White context.paint() # Restore the default source which is black. context.move_to(90, 140) context.rotate(-0.5) context.set_font_size(20) context.show_text('Hi from cairo!') surface.write_to_png('example.png') ``` -------------------------------- ### Install cairocffi with pip Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Install cairocffi using pip. This command will also automatically install CFFI. ```bash pip install cairocffi ``` -------------------------------- ### Using Pango through CFFI with cairocffi Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Illustrates an example of using the Pango C API via CFFI in conjunction with cairocffi. ```APIDOC ## Example: Using Pango through CFFI with cairocffi ### Description This example demonstrates a common use case of CFFI for accessing the Pango C API alongside cairocffi. It highlights how `Context._pointer` can be directly used as an argument for CFFI functions expecting a `cairo_t *`. ### Method The example involves integrating Pango's C API, whose definitions are copied from Pango and GLib documentation, with cairocffi. This approach is presented as an alternative to traditional bindings (like those in PyGTK or PyGObject) and offers access to Pango's full API. ### Example Code ```python # The following code snippet demonstrates using Pango through CFFI with cairocffi. # It is assumed to be in a file named utils/pango_example.py # (Actual code content is omitted as per instructions, but would be here if provided) # # This example showcases direct CFFI interaction with Pango functions # using cairocffi's context pointers. ``` ### Benefits - **Ease of Use**: Simplest for using with cairocffi. - **Full API Access**: Provides access to all of Pango's API, unlike bindings that might only expose a high-level interface. ``` -------------------------------- ### Using Pango C API with CairoFFI Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst This example shows how to use Pango's C API directly via CFFI, integrating with CairoFFI by passing `Context._pointer`. C definitions are copied from Pango and GLib documentation. ```python import cairo import cairocffi from cairocffi import Context # C definitions for Pango and GLib (copied from documentation) # ... (omitted for brevity) # Example usage of Pango functions with cairocffi context # ... (omitted for brevity) ``` -------------------------------- ### Install cairocffi as Pycairo Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Use install_as_pycairo() to make cairocffi the default 'cairo' module. This is useful when you cannot directly change imports in existing code. ```python import cairocffi cairocffi.install_as_pycairo() import cairo assert cairo is cairocffi ``` -------------------------------- ### Converting pycairo to cairocffi Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Provides guidance and an example for converting pycairo Context objects to cairocffi Context wrappers. ```APIDOC ## Converting pycairo wrappers to cairocffi ### Description This section explains how to convert pycairo `cairo.Context` objects to cairocffi `cairo.Context` wrappers. This is useful when working with libraries that provide pycairo objects, allowing you to use them with cairocffi. ### Method The conversion involves extracting the underlying `cairo_t *` pointer from the pycairo context and then using it to create a cairocffi wrapper. This process typically uses unsafe pointer manipulation and is specific to CPython. ### Example ```python # The following function demonstrates the conversion process. # It is assumed to be in a file named utils/pycairo_to_cairocffi.py # (Actual code content is omitted as per instructions, but would be here if provided) # Example usage: # import cairocffi # import cairo # Assuming pycairo is imported as cairo # # # Assume pycairo_context is a cairo.Context object # # pycairo_context = cairo.Context(surface) # # # Convert to cairocffi context # # cairocffi_context = pycairo_to_cairocffi(pycairo_context) ``` ### Note This method only works on CPython. Converting other types of objects like surfaces is similar but left as an exercise. ``` -------------------------------- ### Converting CairoFFI Context to pycairo Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst This example demonstrates converting a CairoFFI `cairo.Context` wrapper to a pycairo `cairo.Context` using ctypes. This approach is sensitive to the GIL. ```python import ctypes from cairocffi import Context def cairocffi_to_pycairo(context): """Convert a cairocffi Context to a pycairo Context. This uses ctypes and is sensitive to the GIL. """ return cairo.Context(context._pointer) ``` -------------------------------- ### Check cairo version compatibility Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Use cairo_version() to check the cairo library version. This example demonstrates checking if the version is greater than 1.10.0 (represented as 11000) before using a method like set_mime_data. ```python if cairocffi.cairo_version() > 11000: surface.set_mime_data('image/jpeg', jpeg_bytes) ``` -------------------------------- ### Apply Transformations with Matrix Source: https://context7.com/kozea/cairocffi/llms.txt Shows how to use context managers for state saving, apply direct matrix transformations, and convert between user and device coordinate spaces. ```python import cairocffi as cairo from math import pi surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 400) context = cairo.Context(surface) context.set_source_rgb(1, 1, 1) context.paint() # Using context manager for save/restore with context: context.translate(100, 100) context.rotate(pi / 4) # 45 degrees context.set_source_rgb(1, 0, 0) context.rectangle(-40, -40, 80, 80) context.fill() # Using Matrix directly matrix = cairo.Matrix() matrix.translate(250, 100) matrix.scale(2, 0.5) # Scale x by 2, y by 0.5 context.set_matrix(matrix) context.set_source_rgb(0, 0, 1) context.arc(0, 0, 40, 0, 2 * pi) # Becomes an ellipse context.fill() # Reset to identity matrix context.identity_matrix() # Coordinate transformation context.translate(200, 250) context.scale(1.5, 1.5) user_x, user_y = 50, 50 device_x, device_y = context.user_to_device(user_x, user_y) print(f"User ({user_x}, {user_y}) -> Device ({device_x}, {device_y})") # Matrix operations m1 = cairo.Matrix(xx=2, yy=2) # Scale matrix m2 = cairo.Matrix.init_rotate(pi / 6) # Rotation matrix combined = m1 * m2 # Multiply matrices print(f"Combined matrix: {combined.as_tuple()}") surface.write_to_png('transforms.png') ``` -------------------------------- ### Update ImageSurface instantiation syntax Source: https://github.com/kozea/cairocffi/blob/main/NEWS.rst Demonstrates the transition from using string-based format identifiers to constant-based identifiers for ImageSurface creation. ```python # Before cairocffi 0.4: surface = cairocffi.ImageSurface('ARGB32', 300, 400) # All cairocffi versions: surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) ``` -------------------------------- ### Initialize an ImageSurface Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Demonstrates the usage of constants from the cairocffi module when initializing a new ImageSurface. ```python surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) ``` -------------------------------- ### Create Gradients and Surface Patterns Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates how to define linear and radial gradients, as well as tiled surface patterns for filling shapes. ```python # Linear gradient linear = cairo.LinearGradient(150, 20, 250, 120) linear.add_color_stop_rgb(0, 1, 0, 0) # Red at start linear.add_color_stop_rgb(0.5, 0, 1, 0) # Green at middle linear.add_color_stop_rgb(1, 0, 0, 1) # Blue at end context.set_source(linear) context.rectangle(150, 20, 100, 100) context.fill() # Radial gradient radial = cairo.RadialGradient(330, 70, 10, 330, 70, 60) radial.add_color_stop_rgba(0, 1, 1, 1, 1) # White center radial.add_color_stop_rgba(1, 0.2, 0.2, 0.8, 1) # Blue edge context.set_source(radial) context.arc(330, 70, 60, 0, 2 * 3.14159) context.fill() # Surface pattern (tiled image) tile = cairo.ImageSurface(cairo.FORMAT_ARGB32, 20, 20) tile_ctx = cairo.Context(tile) tile_ctx.set_source_rgb(0.8, 0.8, 0.8) tile_ctx.paint() tile_ctx.set_source_rgb(0.6, 0.6, 0.6) tile_ctx.rectangle(0, 0, 10, 10) tile_ctx.rectangle(10, 10, 10, 10) tile_ctx.fill() pattern = cairo.SurfacePattern(tile) pattern.set_extend(cairo.EXTEND_REPEAT) context.set_source(pattern) context.rectangle(20, 150, 360, 120) context.fill() surface.write_to_png('patterns.png') ``` -------------------------------- ### Create Image Surface and Draw Source: https://context7.com/kozea/cairocffi/llms.txt Creates an in-memory bitmap image surface, draws on it with a context, and saves it to a PNG file or returns PNG data. ```python import cairocffi as cairo # Create an ARGB32 image surface (300x200 pixels) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200) # Create a drawing context context = cairo.Context(surface) # Fill with white background context.set_source_rgb(1, 1, 1) context.paint() # Draw a red rectangle context.set_source_rgb(1, 0, 0) context.rectangle(50, 50, 100, 80) context.fill() # Save to PNG file surface.write_to_png('output.png') # Or get PNG data as bytes png_data = surface.write_to_png() ``` -------------------------------- ### PostScript Surface Source: https://context7.com/kozea/cairocffi/llms.txt Initializes a PostScript surface for document generation, supporting EPS and specific PS levels. ```python import cairocffi as cairo from io import BytesIO # Create PS surface ps_buffer = BytesIO() surface = cairo.PSSurface(ps_buffer, 595, 842) # A4 size # Set to EPS (Encapsulated PostScript) surface.set_eps(True) # Restrict to PostScript Level 2 surface.restrict_to_level(cairo.PS_LEVEL_2) context = cairo.Context(surface) ``` -------------------------------- ### Drawing Paths and Shapes Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates drawing various paths and shapes including lines, curves, arcs, and rounded rectangles using the Cairo context. ```python import cairocffi as cairo from math import pi, cos, sin surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 400) context = cairo.Context(surface) context.set_source_rgb(1, 1, 1) context.paint() # Draw a star using line_to context.set_source_rgb(1, 0.8, 0) context.move_to(200, 50) for i in range(5): angle = (i * 4 * pi / 5) - pi / 2 context.line_to(200 + 150 * cos(angle), 200 + 150 * sin(angle)) context.close_path() context.fill() # Draw a bezier curve context.set_source_rgb(0.2, 0.2, 0.8) context.set_line_width(4) context.move_to(50, 350) context.curve_to(100, 250, 300, 450, 350, 350) context.stroke() # Draw an arc (partial circle) context.set_source_rgb(0.8, 0.2, 0.2) context.arc(100, 100, 50, 0, pi * 1.5) context.stroke() # Draw a rounded rectangle using arcs def rounded_rect(ctx, x, y, w, h, r): ctx.new_sub_path() ctx.arc(x + w - r, y + r, r, -pi/2, 0) ctx.arc(x + w - r, y + h - r, r, 0, pi/2) ctx.arc(x + r, y + h - r, r, pi/2, pi) ctx.arc(x + r, y + r, r, pi, 3*pi/2) ctx.close_path() context.set_source_rgb(0.2, 0.8, 0.2) rounded_rect(context, 220, 50, 150, 100, 20) context.fill() surface.write_to_png('shapes.png') ``` -------------------------------- ### Accessing Cairo C API via CFFI Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Demonstrates how to access the underlying cairo C API using the `ffi` and `cairo` objects provided by cairocffi. ```APIDOC ## Accessing Cairo C API via CFFI ### Description This section explains how to use the `ffi` and `cairo` objects from cairocffi to interact with the cairo C library directly. The `ffi` object is a CFFI instance with cairo C API declarations, and the `cairo` object is the libcairo library pre-loaded for function access. ### Usage ```python import cairocffi from cairocffi import cairo as cairo_c, SURFACE_TYPE_XLIB # Accessing a cairo function through the cairo_c object # Example: Checking the type of a surface # Assuming 'surface' is a cairocffi Surface object # if cairo_c.cairo_surface_get_type(surface._pointer) == SURFACE_TYPE_XLIB: # ... ``` ### Key Objects - **ffi**: A :external:cffi:doc:`FFI ` instance with all of the cairo C API declared. - **cairo**: The libcairo library, pre-loaded with :external:cffi:ref:`ffi.dlopen() `. All cairo functions are accessible as attributes of this object. ``` -------------------------------- ### Import cairocffi as cairo Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Import cairocffi and alias it as 'cairo' for convenient use, similar to Pycairo. ```python import cairocffi as cairo ``` -------------------------------- ### Working with Colors and Patterns Source: https://context7.com/kozea/cairocffi/llms.txt Applies solid colors with transparency to shapes using set_source_rgba. Supports gradients and patterns for fills and strokes. ```python import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300) context = cairo.Context(surface) # Solid color with alpha context.set_source_rgba(1, 0, 0, 0.5) # 50% transparent red context.rectangle(20, 20, 100, 100) context.fill() ``` -------------------------------- ### Generate PostScript Output with cairocffi Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates configuring a PSSurface, drawing content, and querying supported PostScript levels. ```python # Add DSC comment surface.dsc_comment('%%Title: My Drawing') surface.dsc_begin_setup() surface.dsc_begin_page_setup() # Draw content context.set_source_rgb(0, 0, 0) context.select_font_face('Helvetica') context.set_font_size(24) context.move_to(72, 72) # 1 inch margins context.show_text('PostScript Output') context.set_line_width(2) context.rectangle(72, 100, 451, 200) context.stroke() # Finalize surface.finish() ps_content = ps_buffer.getvalue() # Available PS levels levels = cairo.PSSurface.get_levels() for level in levels: print(f"Supported: {cairo.PSSurface.ps_level_to_string(level)}") ``` -------------------------------- ### Access Raw Pixel Data Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates manual buffer management and direct pixel modification for integration with external libraries. ```python import cairocffi as cairo import array # Create surface with custom data buffer width, height = 200, 150 stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, width) data = array.array('B', [0] * (stride * height)) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height, data, stride) context = cairo.Context(surface) # Draw something context.set_source_rgb(1, 0, 0) context.rectangle(50, 50, 100, 50) context.fill() # Flush to ensure drawing is complete surface.flush() # Access pixel data pixel_data = surface.get_data() print(f"Buffer size: {len(pixel_data)} bytes") print(f"Stride: {surface.get_stride()} bytes per row") print(f"Format: {surface.get_format()}") # Modify pixels directly (native-endian ARGB) surface.flush() raw = surface.get_data() # Set pixel at (0, 0) to green (ARGB in native byte order) import sys if sys.byteorder == 'little': raw[0:4] = bytes([0, 255, 0, 255]) # BGRA for little-endian else: raw[0:4] = bytes([255, 0, 255, 0]) # ARGB for big-endian surface.mark_dirty() surface.write_to_png('pixel_access.png') ``` -------------------------------- ### Import all from cairocffi Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Import all names from cairocffi into the current namespace. This can be used as an alternative to install_as_pycairo() by placing a 'cairo.py' file in sys.path. ```python from cairocffi import * ``` -------------------------------- ### Create PDF Surface and Draw Source: https://context7.com/kozea/cairocffi/llms.txt Generates a PDF document with specified dimensions and metadata. Supports multi-page documents by calling show_page(). ```python import cairocffi as cairo # Create a PDF surface (A4 size: 595x842 points) surface = cairo.PDFSurface('document.pdf', 595, 842) context = cairo.Context(surface) # Set document metadata surface.set_metadata(cairo.PDF_METADATA_TITLE, 'My Document') surface.set_metadata(cairo.PDF_METADATA_AUTHOR, 'John Doe') # Draw on first page context.set_source_rgb(0, 0, 0) context.select_font_face('Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) context.set_font_size(24) context.move_to(50, 50) context.show_text('Page 1') # Create second page context.show_page() context.move_to(50, 50) context.show_text('Page 2') # Finalize the PDF surface.finish() ``` -------------------------------- ### Use Pycairo Compatibility Layer Source: https://context7.com/kozea/cairocffi/llms.txt Configures cairocffi to act as a drop-in replacement for pycairo, allowing existing code to import cairo. ```python import cairocffi # Install as 'cairo' module for compatibility cairocffi.install_as_pycairo() # Now other code can import cairo and get cairocffi import cairo assert cairo is cairocffi # Check versions print(f"cairocffi version: {cairo.VERSION}") print(f"Cairo library version: {cairo.cairo_version_string()}") print(f"Cairo version number: {cairo.cairo_version()}") # Feature detection based on cairo version if cairo.cairo_version() >= 11000: # Use features available since cairo 1.10 surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100) surface.set_mime_data('image/jpeg', b'jpeg-data-here') ``` -------------------------------- ### Render Text and Fonts Source: https://context7.com/kozea/cairocffi/llms.txt Utilizes the toy text API to render, style, and measure text, including converting text to paths for advanced effects. ```python import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 300) context = cairo.Context(surface) context.set_source_rgb(1, 1, 1) context.paint() # Basic text rendering context.set_source_rgb(0, 0, 0) context.select_font_face('Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.set_font_size(24) context.move_to(20, 40) context.show_text('Hello, Cairo!') # Bold and italic text context.select_font_face('Serif', cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD) context.set_font_size(32) context.move_to(20, 90) context.show_text('Bold Italic Serif') # Get text extents for centering context.select_font_face('Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.set_font_size(28) text = "Centered Text" x_bearing, y_bearing, width, height, x_advance, y_advance = context.text_extents(text) x = (500 - width) / 2 - x_bearing context.move_to(x, 150) context.show_text(text) # Text as path (for stroking or filling) context.set_font_size(48) context.move_to(20, 220) context.text_path('Outlined') context.set_source_rgb(0.8, 0.2, 0.2) context.fill_preserve() context.set_source_rgb(0, 0, 0) context.set_line_width(1) context.stroke() # Font extents ascent, descent, height, max_x_advance, max_y_advance = context.font_extents() print(f"Font ascent: {ascent}, descent: {descent}, height: {height}") surface.write_to_png('text.png') ``` -------------------------------- ### Working with PNG Images Source: https://context7.com/kozea/cairocffi/llms.txt Loads PNG images from files or byte streams and applies transformations like scaling and rotation. ```python import cairocffi as cairo from io import BytesIO # Load PNG from file image = cairo.ImageSurface.create_from_png('input.png') width = image.get_width() height = image.get_height() # Load PNG from bytes with open('input.png', 'rb') as f: png_data = f.read() image = cairo.ImageSurface.create_from_png(BytesIO(png_data)) # Create a new surface and composite the image surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300) context = cairo.Context(surface) # White background context.set_source_rgb(1, 1, 1) context.paint() # Draw image at position (50, 50) context.set_source_surface(image, 50, 50) context.paint() # Draw image with scaling context.save() context.translate(200, 50) context.scale(0.5, 0.5) # Half size context.set_source_surface(image, 0, 0) context.paint() context.restore() # Draw image with rotation context.save() context.translate(100, 200) context.rotate(0.3) context.set_source_surface(image, -width/2, -height/2) # Center the image context.paint_with_alpha(0.7) # 70% opacity context.restore() surface.write_to_png('image_composite.png') ``` -------------------------------- ### Converting cairocffi to pycairo Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Explains how to convert cairocffi objects to pycairo objects, using ctypes for compatibility. ```APIDOC ## Converting cairocffi wrappers to pycairo ### Description This section describes the process of converting cairocffi objects back to pycairo objects. This is achieved using `ctypes` to ensure compatibility, especially concerning Python's Global Interpreter Lock (GIL). ### Method The reverse conversion from cairocffi wrappers to pycairo objects is possible. This process utilizes `ctypes` because Python's C API is sensitive to the GIL. ### Example ```python # The following code snippet demonstrates the conversion from cairocffi to pycairo. # It is assumed to be in a file named utils/cairocffi_to_pycairo.py # (Actual code content is omitted as per instructions, but would be here if provided) # Example usage: # import cairocffi # import cairo # Assuming pycairo is imported as cairo # # # Assume cairocffi_context is a cairocffi.Context object # # cairocffi_context = cairocffi.Context(surface) # # # Convert to pycairo context # # pycairo_context = cairocffi_to_pycairo(cairocffi_context) ``` ``` -------------------------------- ### Meta Functions Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Utility functions and exceptions for managing the cairo environment. ```APIDOC ## Meta Functions ### Description Functions to install cairo bindings and retrieve version information. ### Functions - **install_as_pycairo()** - Replaces the pycairo module with cairocffi in sys.modules. - **cairo_version()** - Returns the cairo version as an integer. - **cairo_version_string()** - Returns the cairo version as a string. ### Exceptions - **CairoError** - Base exception for cairo errors. ``` -------------------------------- ### Recording Surface Source: https://context7.com/kozea/cairocffi/llms.txt Captures drawing commands into a RecordingSurface for efficient replay at different scales or positions. ```python import cairocffi as cairo from math import pi # Create a recording surface (unbounded) recording = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None) rec_ctx = cairo.Context(recording) # Draw something rec_ctx.set_source_rgb(0.2, 0.4, 0.8) rec_ctx.arc(50, 50, 40, 0, 2 * pi) rec_ctx.fill() rec_ctx.set_source_rgb(0, 0, 0) rec_ctx.select_font_face('Sans') rec_ctx.set_font_size(14) rec_ctx.move_to(20, 110) rec_ctx.show_text('Recorded') # Get the ink extents (actual drawn area) x, y, width, height = recording.ink_extents() print(f"Recording bounds: ({x}, {y}) {width}x{height}") # Replay onto an image surface multiple times surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 200) context = cairo.Context(surface) context.set_source_rgb(1, 1, 1) context.paint() # Replay at different positions and scales for i in range(3): context.save() context.translate(20 + i * 130, 30) context.scale(1 - i * 0.2, 1 - i * 0.2) context.set_source_surface(recording, 0, 0) context.paint() context.restore() surface.write_to_png('recording.png') ``` -------------------------------- ### Hint Metrics Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Specifies whether to hint font metrics, which involves quantizing them to integer values in device space for consistent spacing. ```APIDOC ## Metrics Hinting Mode Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing. ``` -------------------------------- ### Wrapper Pointer Access Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Shows how to access the underlying C data pointers for various cairocffi wrapper objects. ```APIDOC ## Wrapper Pointer Access ### Description This section lists the attributes that provide direct access to the underlying C data pointers for cairocffi wrapper objects. These pointers are useful when interacting with C functions directly via CFFI. ### Attributes - **Surface._pointer**: The underlying `cairo_surface_t *` cdata pointer. - **Pattern._pointer**: The underlying `cairo_pattern_t *` cdata pointer. - **FontFace._pointer**: The underlying `cairo_font_face_t *` cdata pointer. - **ScaledFont._pointer**: The underlying `cairo_scaled_font_t *` cdata pointer. - **FontOptions._pointer**: The underlying `cairo_scaled_font_t *` cdata pointer. - **Matrix._pointer**: The underlying `cairo_matrix_t *` cdata pointer. - **Context._pointer**: The underlying `cairo_t *` cdata pointer. ``` -------------------------------- ### Antialiasing Modes Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst List of available antialiasing modes and hints for rendering text or shapes. ```APIDOC ## Antialiasing Modes ### Description Specifies the type of antialiasing to perform when rendering text or shapes, including quality hints. ### Modes - **ANTIALIAS_DEFAULT**: Use the default antialiasing for the subsystem and target device. - **ANTIALIAS_NONE**: Use a bilevel alpha mask. - **ANTIALIAS_GRAY**: Perform single-color antialiasing. - **ANTIALIAS_SUBPIXEL**: Perform antialiasing by taking advantage of the order of subpixel elements. ### Hints - **ANTIALIAS_FAST**: Allow the backend to degrade raster quality for speed. - **ANTIALIAS_GOOD**: A balance between speed and quality. - **ANTIALIAS_BEST**: A high-fidelity, but potentially slow, raster mode. ``` -------------------------------- ### Hint Styles Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Specifies the type of hinting to do on font outlines to improve appearance on the pixel grid. ```APIDOC ## Hint Style Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. - `HINT_STYLE_DEFAULT`: Use the default hint style for font backend and target device. - `HINT_STYLE_NONE`: Do not hint outlines. - `HINT_STYLE_SLIGHT`: Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes. - `HINT_STYLE_MEDIUM`: Hint outlines with medium strength, giving a compromise between fidelity to the original shapes and contrast. - `HINT_STYLE_FULL`: Hint outlines to maximize contrast. ``` -------------------------------- ### Load Images with GDK-PixBuf Source: https://context7.com/kozea/cairocffi/llms.txt Uses the pixbuf module to decode image data into a cairo surface, with optional resizing during the load process. ```python import cairocffi as cairo from cairocffi.pixbuf import decode_to_image_surface, ImageLoadingError # Load JPEG image try: with open('photo.jpg', 'rb') as f: image_data = f.read() # Decode to cairo surface (format auto-detected) surface, format_name = decode_to_image_surface(image_data) print(f"Loaded {format_name} image: {surface.get_width()}x{surface.get_height()}") # Optionally resize during load surface_small, _ = decode_to_image_surface(image_data, width=200, height=150) except ImageLoadingError as e: print(f"Failed to load image: {e}") # Use the loaded image canvas = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300) ctx = cairo.Context(canvas) ctx.set_source_surface(surface, 0, 0) ctx.paint() canvas.write_to_png('converted.png') ``` -------------------------------- ### Print cairo version information Source: https://github.com/kozea/cairocffi/blob/main/docs/overview.rst Print the numeric and string representations of the cairo library version, the compatible pycairo version, and the cairocffi version. ```python >>> print("The cairo version is %s, meaning %s." \ ... % (cairocffi.cairo_version(), cairocffi.cairo_version_string())) The cairo version is 11402, meaning 1.14.02. >>> print("The latest pycairo version this cairocffi version is compatible with is %s." \ ... % cairo.version) The latest pycairo version this cairocffi version is compatible with is 1.10.0. >>> print("The cairocffi version is %s." % cairo.VERSION) The cairocffi version is 0.7.2 ``` -------------------------------- ### Implement Clipping Regions Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates restricting drawing operations to a specific circular path using the clip method. ```python import cairocffi as cairo from math import pi surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300) context = cairo.Context(surface) context.set_source_rgb(1, 1, 1) context.paint() # Circular clipping region with context: context.arc(150, 150, 100, 0, 2 * pi) context.clip() # Draw gradient - only visible inside clip gradient = cairo.LinearGradient(50, 50, 250, 250) gradient.add_color_stop_rgb(0, 1, 0, 0) gradient.add_color_stop_rgb(1, 0, 0, 1) context.set_source(gradient) context.paint() # Draw grid - also clipped context.set_source_rgb(0, 0, 0) context.set_line_width(1) for i in range(0, 300, 20): context.move_to(i, 0) context.line_to(i, 300) context.move_to(0, i) context.line_to(300, i) context.stroke() ``` -------------------------------- ### Create SVG Surface and Draw Source: https://context7.com/kozea/cairocffi/llms.txt Generates an SVG file, writing to a BytesIO buffer. Supports setting SVG version and drawing vector graphics. ```python import cairocffi as cairo from io import BytesIO # Create SVG surface (400x300 points) svg_buffer = BytesIO() surface = cairo.SVGSurface(svg_buffer, 400, 300) context = cairo.Context(surface) # Set SVG version surface.restrict_to_version(cairo.SVG_VERSION_1_1) # Draw a circle context.arc(200, 150, 100, 0, 2 * 3.14159) context.set_source_rgb(0.2, 0.4, 0.8) context.fill_preserve() context.set_source_rgb(0, 0, 0) context.set_line_width(3) context.stroke() # Finalize and get SVG content surface.finish() svg_content = svg_buffer.getvalue() ``` -------------------------------- ### Composition Operators Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst List of available operators for defining how source and destination layers interact during rendering. ```APIDOC ## Composition Operators ### Description Defines the behavior for combining source and destination layers during rendering operations. ### Constants - **OPERATOR_CLEAR**: Clear destination layer. - **OPERATOR_SOURCE**: Replace destination layer. - **OPERATOR_OVER**: Draw source layer on top of destination layer. - **OPERATOR_IN**: Draw source where there was destination content. - **OPERATOR_OUT**: Draw source where there was no destination content. - **OPERATOR_ATOP**: Draw source on top of destination content and only there. - **OPERATOR_DEST**: Ignore the source. - **OPERATOR_DEST_OVER**: Draw destination on top of source. - **OPERATOR_DEST_IN**: Leave destination only where there was source content. - **OPERATOR_DEST_OUT**: Leave destination only where there was no source content. - **OPERATOR_DEST_ATOP**: Leave destination on top of source content and only there. - **OPERATOR_XOR**: Source and destination are shown where there is only one of them. - **OPERATOR_ADD**: Source and destination layers are accumulated. - **OPERATOR_SATURATE**: Like OPERATOR_OVER, but assuming source and destination are disjoint geometries. - **OPERATOR_MULTIPLY**: Source and destination layers are multiplied. - **OPERATOR_SCREEN**: Source and destination are complemented and multiplied. - **OPERATOR_OVERLAY**: Multiplies or screens, depending on the lightness of the destination color. - **OPERATOR_DARKEN**: Replaces the destination with the source if it is darker. - **OPERATOR_LIGHTEN**: Replaces the destination with the source if it is lighter. - **OPERATOR_COLOR_DODGE**: Brightens the destination color to reflect the source color. - **OPERATOR_COLOR_BURN**: Darkens the destination color to reflect the source color. - **OPERATOR_HARD_LIGHT**: Multiplies or screens, dependent on source color. - **OPERATOR_SOFT_LIGHT**: Darkens or lightens, dependent on source color. - **OPERATOR_DIFFERENCE**: Takes the difference of the source and destination color. - **OPERATOR_EXCLUSION**: Produces an effect similar to difference, but with lower contrast. - **OPERATOR_HSL_HUE**: Creates a color with the hue of the source and the saturation and luminosity of the target. - **OPERATOR_HSL_SATURATION**: Creates a color with the saturation of the source and the hue and luminosity of the target. - **OPERATOR_HSL_COLOR**: Creates a color with the hue and saturation of the source and the luminosity of the target. - **OPERATOR_HSL_LUMINOSITY**: Creates a color with the luminosity of the source and the hue and saturation of the target. ``` -------------------------------- ### XCBSurface Class Source: https://github.com/kozea/cairocffi/blob/main/docs/xcb.rst The XCBSurface class is used to create graphics surfaces for X windows and pixmaps. ```APIDOC ## XCBSurface ### Description A class within the `cairocffi.xcb` module that allows for the creation of graphics surfaces for X windows and pixmaps using the xcffib library. ### Usage This class is initialized to interface with XCB surfaces, enabling Cairo drawing operations on X11 windows. ``` -------------------------------- ### Converting pycairo Context to CairoFFI Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst This utility function converts a pycairo `cairo.Context` to a CairoFFI wrapper using unsafe pointer manipulation. It is CPython-specific. ```python from cairocffi import Context def pycairo_to_cairocffi(context): """Convert a pycairo Context to a cairocffi Context. This only works on CPython. """ return Context._from_pointer(context.context) ``` -------------------------------- ### Accessing Cairo C API via FFI Source: https://github.com/kozea/cairocffi/blob/main/docs/cffi_api.rst Use the `cairo` object to access libcairo functions and constants. Requires importing cairocffi and potentially specific constants. ```python import cairocffi from cairocffi import cairo as cairo_c, SURFACE_TYPE_XLIB if cairo_c.cairo_surface_get_type(surface._pointer) == SURFACE_TYPE_XLIB: ... ``` -------------------------------- ### Fill Rules Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Specifies how paths are filled. The interpretation is based on ray casting and intersection counts. ```APIDOC ## Fill Rule Used to select how paths are filled. - `FILL_RULE_WINDING`: If the path crosses the ray from left-to-right, counts +1. If from right to left, counts -1. If the total count is non-zero, the point will be filled. - `FILL_RULE_EVEN_ODD`: Counts the total number of intersections. If the total number of intersections is odd, the point will be filled. The default fill rule is `FILL_RULE_WINDING`. ``` -------------------------------- ### Line Join Styles Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Defines how the junction of two lines is rendered when stroking. ```APIDOC ## Line Join Style Specifies how to render the junction of two lines when stroking. - `LINE_JOIN_MITER`: Use a sharp (angled) corner, see `Context.set_miter_limit`. - `LINE_JOIN_ROUND`: Use a rounded join, the center of the circle is the joint point. - `LINE_JOIN_BEVEL`: Use a cut-off join, the join is cut off at half the line width from the joint point. The default line join style is `LINE_JOIN_MITER`. ``` -------------------------------- ### Compositing Operations Source: https://context7.com/kozea/cairocffi/llms.txt Demonstrates how different operators affect the blending of overlapping shapes. ```python import cairocffi as cairo from math import pi surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 400) context = cairo.Context(surface) context.set_source_rgb(0.9, 0.9, 0.9) context.paint() # Demo of common operators operators = [ (cairo.OPERATOR_OVER, "OVER"), (cairo.OPERATOR_SOURCE, "SOURCE"), (cairo.OPERATOR_MULTIPLY, "MULTIPLY"), (cairo.OPERATOR_SCREEN, "SCREEN"), (cairo.OPERATOR_DIFFERENCE, "DIFF"), (cairo.OPERATOR_ADD, "ADD"), ] for i, (op, name) in enumerate(operators): x = 30 + (i % 3) * 160 y = 30 + (i // 3) * 180 with context: context.translate(x, y) # Draw base circle (blue) context.set_operator(cairo.OPERATOR_OVER) context.set_source_rgba(0, 0, 1, 0.8) context.arc(40, 50, 40, 0, 2 * pi) context.fill() # Draw overlapping circle with operator context.set_operator(op) context.set_source_rgba(1, 0, 0, 0.8) context.arc(70, 50, 40, 0, 2 * pi) context.fill() # Label context.set_operator(cairo.OPERATOR_OVER) context.set_source_rgb(0, 0, 0) context.select_font_face('Sans') context.set_font_size(12) context.move_to(25, 110) context.show_text(name) surface.write_to_png('compositing.png') ``` -------------------------------- ### Line Cap Styles Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Defines how the endpoints of a path are rendered when stroking. ```APIDOC ## Line Cap Style Specifies how to render the endpoints of the path when stroking. - `LINE_CAP_BUTT`: Start (stop) the line exactly at the start (end) point. - `LINE_CAP_ROUND`: Use a round ending, the center of the circle is the end point. - `LINE_CAP_SQUARE`: Use squared ending, the center of the square is the end point. The default line cap style is `LINE_CAP_BUTT`. ``` -------------------------------- ### SVG Constants and Units Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Constants representing SVG versions and valid units for coordinates and lengths. ```APIDOC ## SVG Constants ### Description Constants defining SVG versions and units used for coordinates and lengths. ### Data Constants - **SVG_VERSION_1_1** - Version 1.1 of the SVG specification. - **SVG_VERSION_1_2** - Version 1.2 of the SVG specification. ### SVG Units - **SVG_UNIT_USER** - User unit in the current coordinate system. - **SVG_UNIT_EM** - Size of the element's font. - **SVG_UNIT_EX** - X-height of the element's font. - **SVG_UNIT_PX** - Pixels (1px = 1/96th of 1in). - **SVG_UNIT_IN** - Inches (1in = 2.54cm = 96px). - **SVG_UNIT_CM** - Centimeters (1cm = 96px/2.54). - **SVG_UNIT_MM** - Millimeters (1mm = 1/10th of 1cm). - **SVG_UNIT_PT** - Points (1pt = 1/72th of 1in). - **SVG_UNIT_PC** - Picas (1pc = 1/6th of 1in). - **SVG_UNIT_PERCENT** - Percent of a reference value. ``` -------------------------------- ### Pixel Format Constants Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Enumerated constants defining memory formats for image data. ```APIDOC ## Pixel Format Constants ### Description Constants used to identify the memory format of image data in ImageSurface. ### Constants - **FORMAT_ARGB32** - 32-bit ARGB, pre-multiplied alpha. - **FORMAT_RGB24** - 32-bit RGB, upper 8 bits unused. - **FORMAT_A8** - 8-bit alpha. - **FORMAT_A1** - 1-bit alpha. - **FORMAT_RGB16_565** - 16-bit RGB (5-6-5). - **FORMAT_RGB30** - 30-bit RGB, 10 bits per component. ``` -------------------------------- ### Surface Classes Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Classes representing different types of drawing surfaces in cairo. ```APIDOC ## Surface Classes ### Description Base and specialized surface classes for rendering graphics. ### Classes - **Surface** - Base class for all surfaces. - **ImageSurface** - Surface for rendering to memory buffers. - **PDFSurface** - Surface for PDF output. - **PSSurface** - Surface for PostScript output. - **SVGSurface** - Surface for SVG output. - **RecordingSurface** - Surface for recording drawing operations. - **Win32PrintingSurface** - Surface for Windows printing. ``` -------------------------------- ### Antialiasing Modes Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Defines the antialiasing modes available for rendering glyphs. Some modes are mapped to others for compatibility. ```APIDOC ## Antialiasing Modes Used to select the antialiasing mode for rendering. - `ANTIALIAS_FAST`: Fast antialiasing. - `ANTIALIAS_GOOD`: Good quality antialiasing. - `ANTIALIAS_BEST`: Best quality antialiasing. - `ANTIALIAS_GRAY`: Grayscale antialiasing. - `ANTIALIAS_SUBPIXEL`: Subpixel antialiasing. - `ANTIALIAS_DEFAULT`: Default antialiasing mode, typically similar to `ANTIALIAS_GOOD`. ``` -------------------------------- ### Subpixel Order Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Specifies the order of color elements within each pixel for subpixel antialiasing. ```APIDOC ## Subpixel Order The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of `ANTIALIAS_SUBPIXEL`. - `SUBPIXEL_ORDER_DEFAULT`: Use the default subpixel order for the target device. - `SUBPIXEL_ORDER_RGB`: Subpixel elements are arranged horizontally with red at the left. - `SUBPIXEL_ORDER_BGR`: Subpixel elements are arranged horizontally with blue at the left. - `SUBPIXEL_ORDER_VRGB`: Subpixel elements are arranged vertically with red at the top. - `SUBPIXEL_ORDER_VBGR`: Subpixel elements are arranged vertically with blue at the top. ``` -------------------------------- ### Font Weight Styles Source: https://github.com/kozea/cairocffi/blob/main/docs/api.rst Specifies variants of a font face based on their weight. ```APIDOC ## Font Weight Specifies variants of a font face based on their weight. - `FONT_WEIGHT_NORMAL`: Normal font weight. - `FONT_WEIGHT_BOLD`: Bold font weight. ```