[cairo] Creating a pattern

Ravindra rkumar at novell.com
Fri Mar 19 08:27:39 PST 2004

 I want to create different patterns that I can later use to draw/fill
figures. I got two ways to do it. One is based on the knockout example
of Cairo (see code snip1),

// code snip1
void draw_pattern (cairo_t *ct, int forecolor, int backcolor, format)
    cairo_surface_t *hatch;
    int hatch_size = 7;
    int line_width = 1;
    hatch = cairo_surface_create_similar (cairo_current_target_surface
format, hatch_size, hatch_size);

    cairo_surface_set_repeat (hatch, 1);

   /* draw one hatch */
	cairo_save (ct);
	cairo_set_target_surface (ct, hatch);

	/* draw background */
	int R = (backcolor & 0x00FF0000) >> 16;
	int G = (backcolor & 0x0000FF00) >> 8;
	int B = (backcolor & 0x000000FF);
	cairo_set_rgb_color (ct, (double) R / 255.0, (double) G / 255.0,
(double) B / 255.0);

	cairo_rectangle (ct, 0, 0, hatch_size, hatch_size);
	cairo_fill (ct);

	/* draw vertical line in the foreground */
	R = (forecolor & 0x00FF0000) >> 16;
	G = (forecolor & 0x0000FF00) >> 8;
	B = (forecolor & 0x000000FF);
	cairo_set_rgb_color (ct, (double) R / 255.0, (double) G / 255.0,
(double) B / 255.0);

	cairo_set_line_width (ct, line_width);
	cairo_move_to (ct, hatch_size / 2.0, 0);
	cairo_line_to (ct, hatch_size / 2.0, hatch_size);
	cairo_stroke (ct);

	cairo_restore (ct);

/* set the pattern for the consequent fill or stroke */
cairo_set_pattern (ct, hatch);
cairo_surface_destroy (hatch);
// code

This code draws vertical lines those look almost fine. But there are two
problems with this approach. 
a) When we rotate the surface, all small parts that make surface get
rotated and all lines get broken. and 
b) if we draw slanted lines corner to corner, using moveto(0,0) and
lineto(other corner), line parts do not get joined properly. There seems
to a very small space of 1-2 poxels.

Another way, to get this same pattern is to draw lines on the whole big
surface in a loop and then set the surface as pattern. Problem with this
approach is that it's very slow because we fill whole surface with the
lines though we might not be using whole surface in subsequent draw/fill

Could someone please suggest me some way to draw patterns which can be
rotated/scaled without any problem and are not too slow also?

Thanks in advance.

More information about the cairo mailing list