Cairo is a cross platform 2D graphics library. It’s got a wide range of features that are exposed through a solid and easy to use API. From the website:
The cairo API provides operations similar to the drawing operators of PostScript and PDF. Operations in cairo including stroking and filling cubic Bézier splines, transforming and compositing translucent images, and antialiased text rendering. All drawing operations can be transformed by any affine transformation (scale, rotation, shear, etc.)
In today’s post, I’m going to re-implement a very simple version of the old windows screensaver, Mystify. In fact, it’s not even going to look as cool as the one in the video but it will take you through basic drawing with Cairo and animation using GTK+ and GDK.
Getting your feet wet
If you don’t want to dive right into doing animation with Cairo, I suggest that you take a look at the FAQ. Up there is a section on what a minimal C program looks like. For reference, I have included it below. You can see that it’s quite static in nature; writing a PNG of the result at the end:
Building Cairo applications
There’s a shopping list of compiler and linker switches when building with Cairo, GTK+ and GDK. pkg-config has been a great help here, so here are the CFLAGS and LFLAGS definitions from my Makefile:
Setting up the UI
First job is to create a window that will host our drawing. This is all pretty standard boilerplate for any GTK+ application.
The parts to really take note of here is the creation of our drawable, and it getting connected to the window:
Attaching our custom draw function to the draw signal with g_signal_connect:
Setting up a timer with g_timeout_add to continually call the animation function:
Drawing
The Mystify effect is just a handful of vertices bouncing around the screen with lines connecting them. Really quite simple and we can get away with a basic data structure to defined this:
Drawing the structure is just enumerating over the array defined above and drawing the lines: