Pycairo - Creating different shapes

Pycairo - Creating different shapes

Pycairo is a Python module providing bindings for the Cairo graphics library, which is used for creating 2D vector graphics. With Pycairo, you can easily create different shapes like rectangles, circles, lines, and more. Below are examples of how to create various shapes using Pycairo.

Setting Up Pycairo

Before you start, make sure you have Pycairo installed. You can install it using pip:

pip install pycairo 

Creating a Basic Surface

In Pycairo, you start by creating a Surface object. This is where your drawing will be rendered. For these examples, let's create an image surface:

import cairo WIDTH, HEIGHT = 400, 400 # Create an image surface surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) context = cairo.Context(surface) 

Drawing Different Shapes

Rectangle

# Draw a rectangle context.rectangle(50, 50, 100, 100) # (x, y, width, height) context.set_source_rgb(0, 0, 1) # Blue color context.fill() 

Circle

# Draw a circle context.arc(200, 200, 50, 0, 2 * math.pi) # (center_x, center_y, radius, start_angle, end_angle) context.set_source_rgb(1, 0, 0) # Red color context.fill() 

Line

# Draw a line context.move_to(300, 300) # Starting position context.line_to(350, 350) # Ending position context.set_source_rgb(0, 1, 0) # Green color context.set_line_width(5) context.stroke() 

Polygon (e.g., Triangle)

# Draw a triangle context.move_to(100, 300) context.line_to(150, 350) context.line_to(50, 350) context.close_path() # Connects to the starting point context.set_source_rgb(1, 1, 0) # Yellow color context.fill() 

Saving the Image

After drawing, you can save the surface to an image file:

surface.write_to_png("shapes.png") 

Each section above adds a different shape to the surface. You can combine these snippets to draw multiple shapes on the same surface. Remember to set different colors or positions for each shape to distinguish them.


More Tags

http-live-streaming percentage vmware preventdefault zsh-completion jtextfield google-sheets jradiobutton textarea ionicons

More Programming Guides

Other Guides

More Programming Examples