[cairo] Drawing/painting multiple images

Aron Rubin aron.rubin at lmco.com
Fri Aug 29 11:33:20 PDT 2008


Sakari Aaltonen wrote:
> I would like to include several images (PNG's) on a Cairo surface.
> I have seen examples of how to do this with one image, say at
>    http://zetcode.com/tutorials/cairographicstutorial/cairoimages/
> or
>    http://cairographics.org/samples/
> But I cannot figure out the correct way to handle multiple ones.
> My current code looks like this:
> -------------------------------------------------------------
>     cairo_surface_t *surface;
>     double scale = 300;
>     cairo_t *cr;
>     int imagw, imagh;
>     cairo_surface_t *image;
> 
>     surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
>                                          scale, scale);
>     cr = cairo_create(surface);
>     cairo_scale(cr, scale, scale);
>     cairo_set_line_width(cr, 0.10);
> 
>     cairo_set_source_rgb (cr, 0.4, 0.0, 0.6);
>     cairo_rectangle (cr, 0.1, 0.1, 0.5, 0.8);      // rectangle outline
>     cairo_stroke(cr);
> 
>     image = cairo_image_surface_create_from_png ("button.png");
>     imagw = cairo_image_surface_get_width (image);
>     imagh = cairo_image_surface_get_height (image);
>     cairo_scale (cr, 0.15/imagw, 0.15/imagh);
>     cairo_set_source_surface (cr, image, 0, 0);
> 
>     cairo_paint (cr);
>     cairo_surface_destroy (image);
> 
>     cairo_destroy(cr);
>     cairo_surface_destroy (surface);
> ------------------------------------------------------------------
> 
> This seems to work in that <button.png> is drawn. But I don't understand
> how one is supposed to paint another image on the same surface. Or even,
> how to put the single image somewhere else, that is, not at the upper
> left corner.

You can scale and translate the drawing context (cairo_t) or the pattern. The
pattern scaling and translating looks something like this:

pattern = cairo_pattern_create_for_surface (image1);
cairo_pattern_set_filter (pattern, CAIRO_FILTER_GOOD);
sx = ((double)cairo_image_surface_get_width (image1)) / 0.15;
sy = ((double)cairo_image_surface_get_height (image1)) / 0.15;
cairo_matrix_init_scale (&matrix, sx, sy);
cairo_matrix_translate (&matrix, -image1_x, -image1_y);
cairo_pattern_set_matrix (pattern, &matrix);
cairo_set_source (cr, pattern);
cairo_pattern_destroy (pattern);
cairo_paint (cr);

pattern = cairo_pattern_create_for_surface (image2);
cairo_pattern_set_filter (pattern, CAIRO_FILTER_GOOD);
sx = ((double)cairo_image_surface_get_width (image2)) / 0.15;
sy = ((double)cairo_image_surface_get_height (image2)) / 0.15;
cairo_matrix_init_scale (&matrix, sx, sy);
cairo_matrix_translate (&matrix, -image2_x, -image2_y);
cairo_pattern_set_matrix (pattern, &matrix);
cairo_set_source (cr, pattern);
cairo_pattern_destroy (pattern);
cairo_paint (cr);

Aron



More information about the cairo mailing list