Tuesday, September 9, 2008

gtk-stock and gdk_cairo_set_source_pixbuf

It took me the better part of a day to work out how to use a gtk-stock icon as the source for a cairo_paint operation. Basically what I was doing was drawing a magnified section of the screen and painting an eyedropper over it in the middle for the Picksel colorpicker project. I was using a PNG loaded at runtime in the beginning but since GTK has a stock eyedropper icon I figured I might as well use that.

I was having segfault and other issues when I tried gtk_image_create_from_stock and then gtk_image_get_pixmap on the resulting GtkWidget. Apparently the storage method is done in such a way that you can't obtain a GdkPixmap or GdkPixbuf.

What did work though, and actually turned out to be easier was gtk_widget_render_icon. The second and third arguments are the same as the ones used for gtk_image_create_from_stock, the last argument I just left blank, and for the first GtkWidget argument I just passed the reference to my main application window for the stock icon settings to be taken from.

The return from gtk_widget_render_icon is a GdkPixbuf which I used with gdk_cairo_set_source_pixbuf before finally drawing the icon to my destination with cairo_paint.

Here's a brief example.
GtkWidget *window;
GdkPixmap *buffer;
GdkPixbuf *eyedropper;
cairo_t *ctx;

ctx = gdk_cairo_create(buffer);
eyedropper = gtk_widget_render_icon (window, GTK_STOCK_COLOR_PICKER, GTK_ICON_SIZE_MENU, "");
gdk_cairo_set_source_pixbuf (ctx, eyedropper, x, y);

No comments: