Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

PyCairo – How to Create Context Object

  • Last Updated : 23 Jan, 2022

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 :

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!