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
Python
# 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 context.set_line_width( 4 ) # setting of line pattern context.set_dash([ 1.0 ]) # 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 context.stroke() # printing message when file is saved print ( "File Saved" ) |
Output :