Sunday, November 17, 2024
Google search engine
HomeLanguagesPycairo – Creating different shapes

Pycairo – Creating different shapes

In this article we will see how to create different shapes using Pycairo in Python. In pycairo there are mainly two shapes rectangle and the arch which is used to make other shapes like square or semi-circle. Polygon shapes are created with the help of lines. 

An SVG file is a graphics file that uses a two-dimensional graphic vector format that defines images using an XML-based text format. As a standard format for showing vector graphics on the web, SVG files are developed.

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. In order to install the pycairo module we will use the command given below:

pip install pycairo

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.
 

Step-by-step Approach: 

  • Import the pycairo module. 
  • Create an SVG surface object and add context to it. 
  • Using rectangle function create rectangle and square. 
  • Now use the stroke method to remove any moving pen lines to come. 
  • Create a quarter and full circle using arc method inside the stroke so extra line comes.  

Below is the complete program based on the above approach: 

Python3




# importing pycairo
import cairo
  
  
# creating a SVG surface 
# here geek1 is file name & 700, 700 is dimension
with cairo.SVGSurface("geek1.svg", 700, 700) as surface:
      
    # creating a cairo context object
    context = cairo.Context(surface)
      
    #creating a rectangle(square)
    context.rectangle(50, 50, 100, 100)
      
    #creating a rectangle
    context.rectangle(200, 200, 100, 50)
      
    #stroke the context to remove the moved pen 
    context.stroke()
      
    #creating a Arc
    context.arc(330, 60, 40, 500, 2*22/7)
      
     #stroke the context to remove the moved pen 
    context.stroke()
     
     #creating a Circle
    context.arc(500, 60, 40, 0, 2*22/7)
      
      
    # setting scale of the context
    context.scale(700, 700)
      
    # setting line width of the context
    context.set_line_width(0.0025)
      
     # setting color of the context
    context.set_source_rgba(0, 0, 0, 1)
      
    # stroke out the color and width property
    context.stroke()
     


Output :
 

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments