[cairo] Drawing a recurring pattern

M Joonas Pihlaja jpihlaja at cc.helsinki.fi
Sat May 22 02:16:02 PDT 2010


On Fri, 21 May 2010, cool-RR wrote:

> Can you suggest what would be a good way to draw the grid?

I'd probably stroke the grid lines by drawing N+1 horizontal lines and 
M+1 vertical lines across the screen to create an M by N grid.

> What I figured, as a total noob, is to make a `Pattern`, let's says with a
> size of (5, 5), assuming that's the cell size I'm using for my grid, and
> then draw two grey lines, one from (0, 0) to (0, 4) and one from (0, 0) to
> (4, 0).
> 
> Then I use the needed extend style to draw this on my actual context.
> 
> Is this a good way?

You can do this too.  It's nice if you want to be flexible as to the 
actual contents of the grid cell and want to use something mre fancy 
than a wireframe later.  The pattern type you're looking for is a 
surface pattern and the extend mode is CAIRO_EXTEND_REPEAT.  You set 
the position of the repeating grid pattern by using cairo_translate(), 
and then to actually draw the grid, you cairo_set_source() the grid 
pattern to your context and use cairo_rectangle() + cairo_fill() to 
draw the pattern in the area where you want.

Here's an example that does most of the above:

http://cairographics.org/samples/imagepattern/

Hope that helps,

Joonas


More information about the cairo mailing list