Skip to content

Instantly share code, notes, and snippets.

@magcius
Created April 29, 2012 10:47
Show Gist options
  • Save magcius/2549320 to your computer and use it in GitHub Desktop.
Save magcius/2549320 to your computer and use it in GitHub Desktop.
#include <cairo/cairo.h>
#include <math.h>
static void
draw_region (cairo_t *cr,
cairo_region_t *region)
{
cairo_rectangle_int_t box;
int n_boxes, i;
n_boxes = cairo_region_num_rectangles (region);
for (i = 0; i < n_boxes; i++)
{
cairo_region_get_rectangle (region, i, &box);
cairo_rectangle (cr, box.x, box.y, box.width, box.height);
}
}
static void
see_region (cairo_region_t *region,
int width,
int height,
char *filename)
{
cairo_surface_t *surface = cairo_image_surface_create (CAIRO_FORMAT_A8, width, height);
cairo_t *cr = cairo_create (surface);
draw_region (cr, region);
cairo_fill (cr);
cairo_surface_write_to_png (surface, filename);
cairo_destroy (cr);
cairo_surface_destroy (surface);
}
static void
scan_region (cairo_surface_t *surface,
cairo_region_t *union_against)
{
unsigned char *pixels = cairo_image_surface_get_data (surface);
int width = cairo_image_surface_get_width (surface);
int height = cairo_image_surface_get_width (surface);
int stride = cairo_image_surface_get_stride (surface);
int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
int w = x;
while (pixels[y * stride + w] == 255 && w < width)
w++;
if (w > 0)
{
cairo_rectangle_int_t tmp = { x, y, w - x, 1 };
cairo_region_union_rectangle (union_against, &tmp);
x = w;
}
}
}
}
int
main (void)
{
cairo_surface_t *surface;
cairo_region_t *circle_region, *clip_region;
cairo_rectangle_int_t rect = { 0, 0, 500, 500 };
cairo_t *cr;
surface = cairo_image_surface_create (CAIRO_FORMAT_A8, 500, 500);
cr = cairo_create (surface);
cairo_arc (cr, 250, 250, 100, 0, 2 * M_PI);
cairo_fill (cr);
cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR);
cairo_set_source_rgba (cr, 0, 0, 0, 0);
cairo_paint (cr);
cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
cairo_set_source_rgba (cr, 1, 1, 1, 0.5);
circle_region = cairo_region_create ();
cairo_surface_flush (surface);
scan_region (surface, circle_region);
see_region (circle_region, 500, 500, "cairo-a8-circle-region.png");
clip_region = cairo_region_create_rectangle (&rect);
cairo_region_subtract (clip_region, circle_region);
see_region (clip_region, 500, 500, "cairo-a8-clip-region.png");
draw_region (cr, clip_region);
cairo_clip (cr);
cairo_rectangle (cr, 50, 50, 400, 400);
cairo_fill (cr);
cairo_surface_write_to_png (surface, "cairo-a8.png");
cairo_region_destroy (circle_region);
cairo_region_destroy (clip_region);
cairo_destroy (cr);
cairo_surface_destroy (surface);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment