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!
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:
- http://library.gnome.org/devel/gtk/stable/GtkDrawingArea.html
- http://library.gnome.org/devel/gdk/stable/gdk-Cairo-Interaction.html
- http://www.cairographics.org/manual/cairo-cairo-t.html
Examples:
- http://www.tortall.net/mu/wiki/PyGTKCairoTutorial
- http://www.zetcode.com/tutorials/cairographicstutorial/cairoimages/
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.
I would use clutter, for details use the clutter examples, they are pretty nice.
Edit:
If you can not use clutter, you may have a look at cairo which also has some neat examples on the given homepage
You could also use GtkDrawingArea with its Gdk drawing primitives
The best way to do it would be to use a canvas like goocanvas, which is made to work with GTK and draw with cairo. However, it seems it currently only has bindings for C++ and python, so if you're using java, you'll have to find something else...
精彩评论