[cairo] Duplicate surface with different format

Krzysztof Kosiński tweenk.pl at gmail.com
Sat Aug 6 07:38:17 PDT 2011


2011/8/5 Carlos López Camey <c.lopez at kmels.net>:
> I've a GtkDrawingArea and its surface has format CAIRO_FORMAT_INVALID
> by _default_, i.e. "no such format exists or is supported" for that
> surface's data. Is there a way to create a copy of my GtkDrawingArea
> surface with any format I choose? Then I'd be able to query the data
> knowing its format, I'm trying to get a coordinate RGBA values.

The surface of GtkDrawingArea is an X11 surface, not an image surface.
You cannot access its pixels directly, because it's in a different
process (though I it would be possible if Cairo used XShm). To access
the pixels, you need to copy the data to an image surface, e.g.:

// depends on GTK version - in 2.x it's gdk_cairo_create(widget->window);
cairo_t *widget_ct = ...
// w and h can be had from widget's allocation
cairo_surface_t *area_copy = cairo_image_surface_create(w, h,
CAIRO_FORMAT_ARGB32); // get w and h
cairo_t *ct = cairo_create(area_copy);
cairo_set_source_surface(ct, cairo_get_target(widget_ct), 0, 0);
cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE);
cairo_paint(ct);
cairo_destroy(ct);
unsigned char *pixels = cairo_image_surface_get_data(area_copy);
// ...do something with pixels

(Aside: I know that internally there is a backing client-side image
surface for every X11 surface, which handles many operations not
accelerated by the X server. I wonder why this backing surface is not
exposed in Cairo API, even though it appears pixel access to X11
surfaces would be possible in almost all scenarios - either through
reusing the backing surface, or by giving away a pointer directly into
X server's address space through XShm)

Regards, Krzysztof


More information about the cairo mailing list