Rotate a context layer

Import packages

import cairo
import math
from IPython.display import display, Image

Inline functions for displaying

def show_img(file):
    display(Image(filename=file))

Create a rectangle with the rectangle function

# Set some parameters
WIDTH = 200  
HEIGHT = 200  
top_left_x = 50  
top_left_y = 50  
side_length = 100

# Set surface; set background white  
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
context = cairo.Context(surface)
context.set_source_rgb(1, 1, 1)
context.paint()  

# Draw rectangle  
context.set_source_rgb(0, 0, 0)
context.rectangle(top_left_x, top_left_y, side_length, side_length)  
context.stroke()  

surface.write_to_png('rotate_example1.png')
show_img('rotate_example1.png')

Create the same rectangle, rotate rectangle 45 degrees

# Set rotation anchor point (in this example, image center)
rotate_anchor_x = 100 
rotate_anchor_y = 100 

# Set surface; set background white  
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
context = cairo.Context(surface)
context.set_source_rgb(1, 1, 1)
context.paint()  

# Save the current context, rotate context
context.save()
context.translate(rotate_anchor_x,rotate_anchor_y)
context.rotate(45*(math.pi/180)) # needs radians 
context.translate(-rotate_anchor_x,-rotate_anchor_y)


# Draw rectangle, restore to original context  
context.set_source_rgb(0, 0, 0)
context.rectangle(top_left_x, top_left_y, side_length, side_length)  
context.stroke()  
context.restore()

surface.write_to_png('rotate_example2.png')
show_img('rotate_example2.png')

how_to_rotate.ipynb

Written on September 19, 2018