Question

I am trying to understand the cairo_rotate function.

Consider the following code. I would have expected a cross to be drawn, but only the horizontal line (before the rotation) is drawn. What is my mistake?

cairo_move_to(cr,0,HEIGHT/2.); 
cairo_line_to(cr,WIDTH,HEIGHT/2.);
cairo_stroke(cr); //horizontal line
cairo_rotate(cr,90.*(M_PI/180.));
cairo_move_to(cr,0,HEIGHT/2.);
cairo_line_to(cr,WIDTH,HEIGHT/2.);
cairo_stroke(cr); //this line isn't painted
Was it helpful?

Solution

You are rotating around the origin, which is at the top-left corner of the image. To rotate around the center of the image, you must translate as well:

cairo_move_to(cr,0,HEIGHT/2.); 
cairo_line_to(cr,WIDTH,HEIGHT/2.);
cairo_stroke(cr);
cairo_translate(cr,WIDTH/2,HEIGHT/2); // translate origin to the center
cairo_rotate(cr,90.*(M_PI/180.));
cairo_translate(cr,-WIDTH/2,-HEIGHT/2); // translate origin back
cairo_move_to(cr,0,HEIGHT/2.);
cairo_line_to(cr,WIDTH,HEIGHT/2.);
cairo_stroke(cr);

Depending on your application, it might also make sense to actually draw everything relative to the center:

int half_w = WIDTH/2;
int half_h = HEIGHT/2;
cairo_translate(cr, half_w, half_h);
cairo_move_to(cr, -half_w, 0); 
cairo_line_to(cr, half_w, 0);
cairo_stroke(cr); // horizontal line
cairo_rotate(cr, 90.*(M_PI/180.));
cairo_move_to(cr, -half_w, 0);
cairo_line_to(cr, half_w, 0);
cairo_stroke(cr); // vertical line
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top