Search code examples
canvasgtkcairo

An image floating over another


I want to be able to dynamically place images over another image in my app, using Cairo or GTK functions. Imagine, for example, a sea in which the user places fish and sea animals: it will be like that.

How can I do this? If you don't know but remember any simple program or demo that does that, it will be also very welcome!

Thank you!


Solution

  • You can use a GtkDrawingArea and draw the images on it using cairo:

    Example:

    #include <cairo.h>
    #include <gtk/gtk.h>
    
    cairo_surface_t * sea_surface;
    cairo_surface_t * fish_surface;
    
    gboolean on_expose_event(GtkWidget * widget, GdkEventExpose * event, gpointer data) {
        // Create the cairo instance.
        cairo_t * cr = gdk_cairo_create(widget->window);
        // Draw the sea background.
        cairo_set_source_surface(cr, sea_surface, 0.0, 0.0);
        cairo_paint(cr);
        // Draw the fish.
        cairo_set_source_surface(cr, fish_surface, 50.0, 50.0);
        cairo_paint(cr);
        // Destroy the cairo instance.
        cairo_destroy(cr);
        return FALSE;
    }
    
    int main(int argc, char * argv[]) {
        gtk_init(&argc, &argv);
    
        // Load images.
        sea_surface = cairo_image_surface_create_from_png("sea.png");
        fish_surface = cairo_image_surface_create_from_png("fish.png");
    
        // Create window.
        GtkWidget * window;
        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
        gtk_window_set_default_size(GTK_WINDOW(window), 320, 240);  
    
        // Create drawing area where we're going to draw our images.
        GtkWidget * drawing_area = gtk_drawing_area_new();
        g_signal_connect(G_OBJECT(drawing_area), "expose-event", G_CALLBACK(on_expose_event), NULL);
        gtk_container_add(GTK_CONTAINER(window), drawing_area);
    
        // Show window and start gtk main loop.
        gtk_widget_show_all(window);
        gtk_main();
    
        // Clean-up.
        cairo_surface_destroy(fish_surface);
        cairo_surface_destroy(sea_surface);
        return 0;
    }
    

    To compile it on linux use:

    gcc -Wall -g images.c -o images `pkg-config --cflags --libs gtk+-2.0`
    

    Documentation:

    Examples:


    EDIT: If you need to be able to do this from Java, you can use java-gnome which provides bindings for both GTK and cairo.