2011-04-16 49 views
2

我希望能夠從開羅表面製作GtkImage(無需編寫臨時文件)。如何從開羅表面創建GtkImage?

我現在寫的表面,PNG的字符數組,然後我喂到PixbufLoader得到一個pixbuf的,我用它來創建GtkImage:

typedef struct 
{ 
    unsigned char *pos; 
    unsigned char *end; 
} closure_t; 

static cairo_status_t 
png_to_array (void *closure, const unsigned char *data, unsigned int length) 
{ 
    closure_t *cl = (closure_t *) closure; 

    if ((cl->pos + length) > (cl->end)) 
     return CAIRO_STATUS_WRITE_ERROR; 

    memcpy (cl->pos, data, length); 
    cl->pos += length; 

    return CAIRO_STATUS_SUCCESS; 
} 


// later in the code 
cairo_surface_t *surface = ... 

... 

// how would i determine the right size? 
unsigned char arr[...]; 
closure_t cl; 
GtkWidget *image; 
GdkPixbufLoader *pbloader; 
GdkPixbuf *pb; 

// copy surface png to arr 
cl.pos = arr; 
cl.end = arr + sizeof(arr); 
cairo_surface_write_to_png_stream (surface, 
        (cairo_write_func_t) png_to_array, 
        &cl); 

... 
// write to pixbufloader, get pixbuf, create image 
pbloader = gdk_pixbuf_loader_new(); 
gdk_pixbuf_loader_write(pbloader, arr, sizeof(arr), NULL); 
gdk_pixbuf_loader_close(pbloader, NULL); 

pb = gdk_pixbuf_loader_get_pixbuf(pbloader); 

image = gtk_image_new_from_pixbuf(pb); 
  1. 這似乎相當麻煩 - ISN」有沒有更簡單的方法來做到這一點?
  2. 我如何確定我的例子中的數組的大小?

回答

0

一個函數將爲您節省大量的精力。查找gdk_pixbuf_get_from_surface。它從cairo_surface_t獲得一個Pixbuf。當他寫這篇文章的時候,只有在使用Gdk-3.0的時候纔可以使用,這也意味着使用Gtk + -3.0。

粗,如果你想使用GTK + -2.0,那麼你可以創建一個像素圖,得到cairo_t從中再由

cairo_set_source_surface (cr, surface, x0, y0); 
cairo_rectangle (cr, x0 + x, y0 + y, width, height); 
cairo_fill (cr); 

你的其他cairo_surface_t複製到如何創建一個像素圖是一個例子下面,我會讓你填寫其餘的。

#include <gtk/gtk.h> 
#include <cairo/cairo.h> 


int main(gint argc, gchar *argv[]) 
{ 
    GdkPixmap *pixmap; 
    GtkWidget *image; 
    GtkWidget *window; 
    cairo_t *cr; 

    gtk_init(&argc, &argv); 

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL); 
    g_signal_connect(G_OBJECT(window), "delete-event", G_CALLBACK(gtk_main_quit), NULL); 

    gtk_widget_show_all(window); 

    pixmap = gdk_pixmap_new(window->window, 100, 100, -1); 
    cr = gdk_cairo_create(pixmap); 
    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);  
    cairo_rectangle(cr, 10, 10, 80, 80); 
    cairo_fill(cr); 
    cairo_destroy(cr); 

    cr = NULL; 



    image = gtk_image_new_from_pixmap(pixmap, NULL); 

    gtk_container_add(GTK_CONTAINER(window), image); 


    gtk_widget_show(image); 



    gtk_main(); 

    return 0; 
}