tvaz
tvaz

Reputation: 107

Make objects move in Cairo

I need to use Cairo to make geometric formulas move through the screen.

How does one "move" objects (like circles) in Cairo? I did try cairo_translate(cr, x, y) function but it seems to change the referential for all the objects and I don't know how to produce de "movement". In other frameworks I would increment the x value and change the speed with an appropriate clock() function to control FPS's, then I would paint the drawing area background and draw the object with new coordinates.

But I don't know how to produce this with Cairo and all documentation I can find does not mention how this is done.

This is the code I have:

genRandVector(numOfBalls);

/* creates big ball */
cairo_set_line_width(cr, 5);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_arc(cr, balls_MAP[0].x, balls_MAP[0].y, CONF.big_rad, 0, 2 * M_PI);

cairo_stroke_preserve(cr);
cairo_set_source_rgb(cr, 0.9, 0.9, 0.9);

cairo_fill(cr);

/* creates other balls */
int i;
cairo_close_path(cr);
cairo_set_source_rgb(cr, 0, 0, 0);

for(i = 1; i < numOfBalls; i++) {

    cairo_arc(cr, balls_MAP[i].x, balls_MAP[i].y, CONF.small_rad, 0, 2 * M_PI);
    cairo_stroke_preserve(cr);

    cairo_fill(cr);
    cairo_close_path(cr);
}

And my circles are still. I would like to make all of them move randomly. I just don't know how to make them "move".

Upvotes: 0

Views: 1238

Answers (1)

andlabs
andlabs

Reputation: 11578

cairo doesn't animate things, and it doesn't have the concept of objects. Using cairo is more like using a paintbrush on a canvas: once you draw something onto the canvas, it's stuck there and you can't refer to it to change its properties at all, let alone move it around.

Therefore, to animate things drawn with cairo, you have to wipe the part of the canvas that's being animated and draw it again. How to do that depends on what toolkit you are using to display your graphics.

From the tags, I assume you are using GTK+. There are several methods of GtkWidget, such as gtk_widget_queue_draw() and gtk_widget_queue_draw_area(), that will schedule a redraw of your widget. Call this in a g_timeout_add() handler to schedule your animation. You'll get a drawing signal (the same one you're using already) for the portion of the GtkWidget that you chose to redraw (which you can get from within the draw handler with cairo_clip_extents()). Since the relevant portion of the canvas will be blanked already when you enter the draw handler, you can just start drawing your next frame.

You may wish to consider using a dedicated animation framework instead if your needs are sufficiently complicated. Clutter is one specifically designed to be used with GTK+, but there are also others.

Upvotes: 1

Related Questions