CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pycairo

Python interface for cairo graphics library providing 2D vector graphics, drawing operations, and rendering to multiple output formats

Pending
Overview
Eval results
Files

drawing-context.mddocs/

Drawing Context

The Context class provides the central interface for all Cairo drawing operations. It maintains the current drawing state including path, colors, line styles, transformations, and clipping regions. Context objects are created with a target Surface and provide methods for path construction, painting, stroking, and state management.

Capabilities

Context Creation and State Management

class Context:
    def __init__(self, target: Surface) -> None:
        """Create a new Context for the target surface.
        
        Args:
            target: The surface to draw on
        """
        
    def save(self) -> None:
        """Save the current graphics state to an internal stack."""
        
    def restore(self) -> None:
        """Restore the graphics state from the most recently saved state."""
        
    def get_target(self) -> Surface:
        """Get the target surface for the context."""
        
    def push_group(self) -> None:
        """Temporarily redirect drawing to an intermediate surface."""
        
    def push_group_with_content(self, content: Content) -> None:
        """Push a group with specific content type."""
        
    def pop_group(self) -> SurfacePattern:
        """Pop the group and return it as a pattern."""
        
    def pop_group_to_source(self) -> None:
        """Pop the group and set it as the source pattern."""

Color and Source Setting

def set_source_rgb(self, red: float, green: float, blue: float) -> None:
    """Set the source pattern to an opaque RGB color.
    
    Args:
        red: Red component (0.0 to 1.0)
        green: Green component (0.0 to 1.0)
        blue: Blue component (0.0 to 1.0)
    """
    
def set_source_rgba(self, red: float, green: float, blue: float, alpha: float) -> None:
    """Set the source pattern to a translucent RGBA color.
    
    Args:
        red: Red component (0.0 to 1.0)
        green: Green component (0.0 to 1.0) 
        blue: Blue component (0.0 to 1.0)
        alpha: Alpha component (0.0 to 1.0)
    """
    
def set_source(self, source: Pattern) -> None:
    """Set the source pattern for drawing operations."""
    
def set_source_surface(self, surface: Surface, x: float = 0.0, y: float = 0.0) -> None:
    """Set a surface as the source pattern with optional offset."""
    
def get_source(self) -> Pattern:
    """Get the current source pattern."""

Path Construction

def new_path(self) -> None:
    """Clear the current path and begin a new empty path."""
    
def new_sub_path(self) -> None:
    """Begin a new sub-path within the current path."""
    
def close_path(self) -> None:
    """Add a line segment from current point to the start of current sub-path."""
    
def move_to(self, x: float, y: float) -> None:
    """Begin a new sub-path at the given point."""
    
def line_to(self, x: float, y: float) -> None:
    """Add a line to the path from current point to given point."""
    
def curve_to(self, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float) -> None:
    """Add a cubic Bézier spline to the path."""
    
def arc(self, xc: float, yc: float, radius: float, angle1: float, angle2: float) -> None:
    """Add a circular arc to the path.
    
    Args:
        xc: X coordinate of center
        yc: Y coordinate of center  
        radius: Radius of the arc
        angle1: Start angle in radians
        angle2: End angle in radians
    """
    
def arc_negative(self, xc: float, yc: float, radius: float, angle1: float, angle2: float) -> None:
    """Add a circular arc in the negative direction."""
    
def rectangle(self, x: float, y: float, width: float, height: float) -> None:
    """Add a rectangle to the path."""
    
def rel_move_to(self, dx: float, dy: float) -> None:
    """Begin a new sub-path at a point relative to current point."""
    
def rel_line_to(self, dx: float, dy: float) -> None:
    """Add a line to the path relative to current point."""
    
def rel_curve_to(self, dx1: float, dy1: float, dx2: float, dy2: float, dx3: float, dy3: float) -> None:
    """Add a cubic Bézier spline relative to current point."""
    
def text_path(self, text: str) -> None:
    """Add closed paths for text to the current path."""
    
def glyph_path(self, glyphs: list[Glyph]) -> None:
    """Add closed paths for glyphs to the current path."""

Path Information and Manipulation

def get_current_point(self) -> tuple[float, float]:
    """Get the current point in the path."""
    
def has_current_point(self) -> bool:
    """Check if there is a current point defined."""
    
def copy_path(self) -> Path:
    """Create a copy of the current path."""
    
def copy_path_flat(self) -> Path:
    """Create a flattened copy of the current path."""
    
def append_path(self, path: Path) -> None:
    """Append a path to the current path."""
    
def path_extents(self) -> tuple[float, float, float, float]:
    """Compute bounding box of current path."""

Drawing Operations

def fill(self) -> None:
    """Fill the current path with the current source pattern."""
    
def fill_preserve(self) -> None:
    """Fill the current path and preserve the path for further operations."""
    
def fill_extents(self) -> tuple[float, float, float, float]:
    """Compute bounding box that would be affected by fill operation."""
    
def in_fill(self, x: float, y: float) -> bool:
    """Test if point would be affected by fill operation."""
    
def stroke(self) -> None:
    """Stroke the current path with the current source pattern."""
    
def stroke_preserve(self) -> None:
    """Stroke the current path and preserve the path."""
    
def stroke_extents(self) -> tuple[float, float, float, float]:
    """Compute bounding box that would be affected by stroke operation."""
    
def in_stroke(self, x: float, y: float) -> bool:
    """Test if point would be affected by stroke operation."""
    
def paint(self) -> None:
    """Paint entire surface with current source pattern."""
    
def paint_with_alpha(self, alpha: float) -> None:
    """Paint entire surface with current source pattern using alpha."""

Line and Stroke Properties

def set_line_width(self, width: float) -> None:
    """Set the line width for stroking operations."""
    
def get_line_width(self) -> float:
    """Get the current line width."""
    
def set_line_cap(self, line_cap: LineCap) -> None:
    """Set the line cap style."""
    
def get_line_cap(self) -> LineCap:
    """Get the current line cap style."""
    
def set_line_join(self, line_join: LineJoin) -> None:
    """Set the line join style."""
    
def get_line_join(self) -> LineJoin:
    """Get the current line join style."""
    
def set_miter_limit(self, limit: float) -> None:
    """Set the miter limit for line joins."""
    
def get_miter_limit(self) -> float:
    """Get the current miter limit."""
    
def set_dash(self, dashes: list[float], offset: float = 0.0) -> None:
    """Set dash pattern for line stroking."""
    
def get_dash(self) -> tuple[list[float], float]:
    """Get current dash pattern and offset."""
    
def get_dash_count(self) -> int:
    """Get number of dashes in current dash pattern."""
    
def set_hairline(self, set_hairline: bool) -> None:
    """Enable or disable hairline mode for 1-pixel wide lines."""
    
def get_hairline(self) -> bool:
    """Get current hairline mode setting."""

Transformations

def translate(self, tx: float, ty: float) -> None:
    """Modify transformation matrix to translate by given amounts."""
    
def scale(self, sx: float, sy: float) -> None:
    """Modify transformation matrix to scale by given factors."""
    
def rotate(self, angle: float) -> None:
    """Modify transformation matrix to rotate by given angle in radians."""
    
def transform(self, matrix: Matrix) -> None:
    """Apply transformation matrix to current transformation."""
    
def set_matrix(self, matrix: Matrix) -> None:
    """Set the current transformation matrix."""
    
def get_matrix(self) -> Matrix:
    """Get the current transformation matrix."""
    
def identity_matrix(self) -> None:
    """Reset transformation matrix to identity."""
    
def user_to_device(self, x: float, y: float) -> tuple[float, float]:
    """Transform point from user space to device space."""
    
def user_to_device_distance(self, dx: float, dy: float) -> tuple[float, float]:
    """Transform distance from user space to device space."""
    
def device_to_user(self, x: float, y: float) -> tuple[float, float]:
    """Transform point from device space to user space."""
    
def device_to_user_distance(self, dx: float, dy: float) -> tuple[float, float]:
    """Transform distance from device space to user space."""

Clipping

def clip(self) -> None:
    """Establish clipping region from current path."""
    
def clip_preserve(self) -> None:
    """Establish clipping region and preserve current path."""
    
def clip_extents(self) -> tuple[float, float, float, float]:
    """Get bounding box of current clipping region."""
    
def in_clip(self, x: float, y: float) -> bool:
    """Test if point is inside current clipping region."""
    
def reset_clip(self) -> None:
    """Reset clipping region to unlimited."""
    
def copy_clip_rectangle_list(self) -> list[Rectangle]:
    """Get list of rectangles covering current clipping region."""

Compositing and Blending

def set_operator(self, operator: Operator) -> None:
    """Set compositing operator for drawing operations."""
    
def get_operator(self) -> Operator:
    """Get current compositing operator."""
    
def set_tolerance(self, tolerance: float) -> None:
    """Set tolerance for curve flattening."""
    
def get_tolerance(self) -> float:
    """Get current tolerance value."""
    
def set_antialias(self, antialias: Antialias) -> None:
    """Set antialiasing mode."""
    
def get_antialias(self) -> Antialias:
    """Get current antialiasing mode."""
    
def set_fill_rule(self, fill_rule: FillRule) -> None:
    """Set fill rule for path filling."""
    
def get_fill_rule(self) -> FillRule:
    """Get current fill rule."""

PDF Tagging Support

def tag_begin(self, tag_name: str, attributes: str) -> None:
    """Begin a tagged content sequence for PDF accessibility.
    
    Args:
        tag_name: Name of the tag (e.g., 'P', 'H1', 'Link')
        attributes: Tag attributes as string
    """
    
def tag_end(self, tag_name: str) -> None:
    """End a tagged content sequence.
    
    Args:
        tag_name: Name of the tag to close
    """

Text Rendering

def select_font_face(self, family: str, slant: FontSlant, weight: FontWeight) -> None:
    """Select a font face for text rendering."""
    
def set_font_size(self, size: float) -> None:
    """Set font size for text rendering."""
    
def set_font_matrix(self, matrix: Matrix) -> None:
    """Set font transformation matrix."""
    
def get_font_matrix(self) -> Matrix:
    """Get current font transformation matrix."""
    
def set_font_options(self, options: FontOptions) -> None:
    """Set font rendering options."""
    
def get_font_options(self) -> FontOptions:
    """Get current font rendering options."""
    
def set_font_face(self, font_face: FontFace) -> None:
    """Set font face for text rendering."""
    
def get_font_face(self) -> FontFace:
    """Get current font face."""
    
def set_scaled_font(self, scaled_font: ScaledFont) -> None:
    """Set scaled font for text rendering."""
    
def get_scaled_font(self) -> ScaledFont:
    """Get current scaled font."""
    
def show_text(self, text: str) -> None:
    """Render text at current point."""
    
def show_glyphs(self, glyphs: list[Glyph]) -> None:
    """Render glyphs at specified positions."""
    
def show_text_glyphs(self, text: str, glyphs: list[Glyph], clusters: list[TextCluster], cluster_flags: TextClusterFlags) -> None:
    """Render text with glyph and cluster information for advanced typography."""
    
def text_extents(self, text: str) -> TextExtents:
    """Get extents of text using current font."""
    
def glyph_extents(self, glyphs: list[Glyph]) -> TextExtents:
    """Get extents of glyphs using current font."""
    
def font_extents(self) -> tuple[float, float, float, float, float]:
    """Get metrics of current font."""

Usage Examples

Basic Drawing Operations

import cairo

# Create surface and context
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)

# Set background
ctx.set_source_rgb(1, 1, 1)
ctx.paint()

# Draw and fill a rectangle
ctx.set_source_rgb(0.8, 0.2, 0.2)
ctx.rectangle(50, 50, 100, 80)
ctx.fill()

# Draw and stroke a circle
ctx.set_source_rgb(0.2, 0.2, 0.8)
ctx.arc(200, 150, 40, 0, 2 * 3.14159)
ctx.set_line_width(3)
ctx.stroke()

surface.write_to_png("basic_drawing.png")

Complex Path with Curves

import cairo
import math

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)

# Create a complex path with curves
ctx.move_to(50, 150)
ctx.curve_to(50, 50, 150, 50, 150, 150)
ctx.curve_to(150, 250, 250, 250, 250, 150)
ctx.line_to(350, 150)

# Stroke the path
ctx.set_source_rgb(0, 0, 0)
ctx.set_line_width(2)
ctx.stroke()

surface.write_to_png("complex_path.png")

Transformations and Clipping

import cairo
import math

surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
ctx = cairo.Context(surface)

# Save state and apply transformations
ctx.save()
ctx.translate(200, 150)
ctx.rotate(math.pi / 4)
ctx.scale(1.5, 0.8)

# Create clipping region
ctx.arc(0, 0, 50, 0, 2 * math.pi)
ctx.clip()

# Draw something that will be clipped
ctx.set_source_rgb(0.8, 0.4, 0.2)
ctx.rectangle(-80, -80, 160, 160)
ctx.fill()

# Restore state
ctx.restore()

surface.write_to_png("transforms_clipping.png")

Install with Tessl CLI

npx tessl i tessl/pypi-pycairo

docs

constants-enums.md

drawing-context.md

geometry.md

index.md

patterns.md

surfaces.md

text-fonts.md

tile.json