我正在使用gtk3和c
int main(int argc, char *argv[])
{
out = output_exemple();
//out = k_medoide(in,out);
GtkBuilder *gtkBuilder;
GtkWidget *window;
GtkWidget *entry1, *entry2, *vbox, *button1, *button2, *drawing_area;
//initialisation gtk
gtk_init(&argc, &argv);
//instanciation des objet
gtkBuilder = gtk_builder_new();
gtk_builder_add_from_file(gtkBuilder, "sample.glade", NULL);
//load controls from the glade
window = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "window1"));
button1 = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "button1"));
vbox = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "vbox1"));
drawing_area = gtk_drawing_area_new ();
gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
gtk_widget_set_size_request(drawing_area, 400, 400);
gtk_box_pack_end(GTK_BOX(vbox),drawing_area,0,0,0);
//declaration des evenements
g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);
g_signal_connect(button1,"clicked",G_CALLBACK(button_n_clicked), drawing_area);
g_signal_connect(entry1,"insert-at-cursor",G_CALLBACK(entry_clicked),NULL);
g_signal_connect (drawing_area, "draw", G_CALLBACK (draw_cb), NULL);
g_signal_connect (drawing_area,"configure-event", G_CALLBACK (configure_event_cb), NULL);
g_object_unref(G_OBJECT(gtkBuilder));
gtk_widget_show_all(window);
gtk_main();
return 0;
}
这是事件函数
static gboolean configure_event_cb (GtkWidget *widget, GdkEventConfigure *event, gpointer data)
{
if (surface)
cairo_surface_destroy (surface);
surface = cairo_image_surface_create_from_png("a.png");
cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 100, 100);
//Create the cairo context
cairo_t *cr = cairo_create(img);
//Initialize the image to black transparent
cairo_set_source_rgba(cr, 0,0,0, 1);
cairo_paint(cr);
//Paint one image
cairo_set_source_surface(cr, surface, 0, 0);
cairo_paint(cr);
return TRUE;
}
static gboolean draw_cb (GtkWidget *widget, cairo_t *cr, gpointer data)
{
cairo_set_source_surface (cr, surface, 0, 0);
cairo_paint (cr);
return FALSE;
}
当点击按钮时,我在循环中绘制一些矩形,我想在循环的每次迭代中重绘绘图区域。
ps:gtk_widget_queue_draw()仅在返回gtk_main()时更新drawingarea;
static void button_n_clicked(GtkWidget *widget, gpointer data[]){
cairo_region_t *cr;
cr = cairo_create (surface);
gtk_widget_queue_draw (data[1]); //data[1] = drawing_area
int n = 15;
clear_surface();
int i, x, y;
srand ( time(NULL) );
if (surface == NULL)
return FALSE;
for(i=0;i<n;i++){
x=8+rand()%560;
y=8+rand()%380;
draw_brush (data[1], x, y);
cairo_rectangle (cr, x, y, 3, 3);
cairo_fill (cr);
}
cairo_destroy (cr);
return TRUE;
}