Other Surfaces

Learn about the uses of surfaces that are not used to create output.

We'll cover the following...

RecordingSurface

A recording surface records drawing operations, which can later be played back to a normal surface. Here is an example of this:

Press + to interact
import cairo
# Recorded page
rec_surface = cairo.RecordingSurface(cairo.Content.COLOR, None)
ctx=cairo.Context(rec_surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
ctx.rectangle(100, 100, 200, 200)
ctx.set_source_rgb(1, 0, 0)
ctx.fill()
# Page 1
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 400)
ctx=cairo.Context(surface)
ctx.set_source_surface(rec_surface)
ctx.paint()
ctx.set_source_rgb(0, 0, 0)
ctx.move_to(500, 350)
ctx.set_font_size(20)
ctx.show_text('Page1')
surface.write_to_png('output/page1.png')
# Page 2
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 600, 400)
ctx=cairo.Context(surface)
ctx.set_source_surface(rec_surface)
ctx.paint()
ctx.set_source_rgb(0, 0, 0)
ctx.move_to(500, 350)
ctx.set_font_size(20)
ctx.show_text('Page2')
surface.write_to_png('output/page2.png')

First, we create a RecordingSurface. This takes two parameters:

  • content defines the type of content we want to record. This is set by a cairo.Content value of COLOR, ALPHA, or COLOR_ALPHA (to record color and alpha information)

  • ...