Skip to content

Instantly share code, notes, and snippets.

@rickardlindberg
Created May 20, 2023 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickardlindberg/d3975038cd1c93b7846e82896c682bbe to your computer and use it in GitHub Desktop.
Save rickardlindberg/d3975038cd1c93b7846e82896c682bbe to your computer and use it in GitHub Desktop.
Example how to display images drawn with Cairo in Pygame.
import cairo
import pygame
import sys
SIZE = (400, 400)
def draw_frame(cairo_context, position):
cairo_context.set_source_rgb(1, 0, 0)
cairo_context.rectangle(position, position, 10, 10)
cairo_context.fill()
def loop():
pygame.init()
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
position = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
cairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *SIZE)
draw_frame(cairo.Context(cairo_surface), position)
screen.fill("black")
screen.blit(
pygame.image.frombuffer(cairo_surface.get_data(), SIZE, "BGRA"),
(0, 0)
)
pygame.display.flip()
clock.tick(60)
position = (position + 1) % (SIZE[0]-10)
if __name__ == "__main__":
loop()
@rickardlindberg
Copy link
Author

$ python
Python 3.9.10 (main, Jan 17 2022, 00:00:00) 
[GCC 11.2.1 20210728 (Red Hat 11.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 2.3.0 (SDL 2.24.2, Python 3.9.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> import cairo
>>> cairo.version
'1.20.1'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment