I wanted to use pyCairo with pyGame but can’t find any sample on the net.

So, here is a little bit of code to do this without using pyGTK.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
import cairo 
import pygame 
import array 
import math 

def draw(surface): 
    x,y, radius = (250,250, 200) 
    ctx = cairo.Context(surface) 
    ctx.set_line_width(15) 
    ctx.arc(x, y, radius, 0, 2.0 * math.pi) 
    ctx.set_source_rgb(0.8, 0.8, 0.8) 
    ctx.fill_preserve() 
    ctx.set_source_rgb(1, 1, 1) 
    ctx.stroke() 
    
def input(events): 
    for event in events: 
        if event.type == pygame.QUIT: 
            sys.exit(0) 
        else: 
            print event 
            
#Create Cairo Surface 
Width, Height = 512, 512 
data = array.array('c', chr(0) * Width * Height * 4) 
stride = Width * 4 
surface = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_ARGB32,Width, Height, stride) 

#init PyGame 
pygame.init() 
window = pygame.display.set_mode( (Width,Height) ) 
screen = pygame.display.get_surface() 

#Draw with Cairo 
draw(surface) 

#Create PyGame surface from Cairo Surface 
image = pygame.image.frombuffer(data.tostring(),(Width,Height),"ARGB",) 

#Tranfer to Screen 
screen.blit(image, (0,0)) 
pygame.display.flip() 
while True: 
    input(pygame.event.get())

Notes

  • This is working on Linux and Windows.
  • I’m using pyGame 1.7.1. There seems to be a bug in the surface creation with the “ARGB” byte order…