Open In App
Related Articles

PyCairo – How to Create Context Object

Like Article
Save Article
Report issue

In this article we will see how we can create context object in pycairo python. Pycairo is a Python module providing bindings for the cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. Context is the main object used when drawing with cairo. To draw with cairo, you create a Context, set the target surface, and drawing options for the Context, create shapes with functions like context.set_source_rgba( ), context.set_line_width( ), context.set_dash( ), context.move_to( ), context.rectangle( ) or context.stroke( ).

In order to this we will use Context method

Syntax : cairo.Context(surface)

Argument : It takes target surface for the context

Return : It returns a newly allocated Context


# importing pycairo
import cairo
# creating a SVG surface
# here geekline is file name & 700, 700 is dimension
with cairo.SVGSurface("geekline.svg", 700, 700) as surface:
    # creating a cairo context object for SVG surface
    # using Context method
    context = cairo.Context(surface)
    # setting color of the context
    context.set_source_rgba(0, 0, 0, 1)
    # setting of line width
    # setting of line pattern
    # move the context to x,y position
    context.move_to(40, 30)
    # creating a rectangle(square)
    context.rectangle(100, 100, 100, 100)
    # stroke out the color and width property
# printing message when file is saved
print("File Saved")

Output :

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Jan, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials