我正在尝试修改在http://zetcode.com/gfx/cairo/basicdrawing/中找到的cairo图形渲染,以便在我用鼠标左键单击绘图区域时更新图形。当前,该网站中的代码使用鼠标右键单击来更新图形。
我尝试在 event-> button == 1 时将 gtk_widget_queue_draw(widget); 添加到 gboolean clicked():>
#include <cairo.h>
#include <gtk/gtk.h>
static void do_drawing(cairo_t *);
struct {
int count;
double coordx[100];
double coordy[100];
} glob;
static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr,
gpointer user_data)
{
do_drawing(cr);
return FALSE;
}
static void do_drawing(cairo_t *cr)
{
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 0.5);
int i, j;
for (i = 0; i <= glob.count - 1; i++ ) {
for (j = 0; j <= glob.count - 1; j++ ) {
cairo_move_to(cr, glob.coordx[i], glob.coordy[i]);
cairo_line_to(cr, glob.coordx[j], glob.coordy[j]);
}
}
glob.count = 0;
cairo_stroke(cr);
}
static gboolean clicked(GtkWidget *widget, GdkEventButton *event,
gpointer user_data)
{
if (event->button == 1) {
glob.coordx[glob.count] = event->x;
glob.coordy[glob.count++] = event->y;
gtk_widget_queue_draw(widget);
}
if (event->button == 3) {
gtk_widget_queue_draw(widget);
}
return TRUE;
}
int main(int argc, char *argv[])
{
GtkWidget *window;
GtkWidget *darea;
glob.count = 0;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
darea = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), darea);
gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);
g_signal_connect(G_OBJECT(darea), "draw",
G_CALLBACK(on_draw_event), NULL);
g_signal_connect(window, "destroy",
G_CALLBACK(gtk_main_quit), NULL);
g_signal_connect(window, "button-press-event",
G_CALLBACK(clicked), NULL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
gtk_window_set_title(GTK_WINDOW(window), "Lines");
gtk_widget_show_all(window);
gtk_main();
return 0;
}
但是,由于现在根本不更新图形,所以这不起作用。
是否可以通过按鼠标左键(按钮1)来更新图形,并像以前一样同时将坐标插入到结构 glob 中?
谢谢!
答案 0 :(得分:1)
您要在绘制线条之后设置glob.count = 0
,但是glob.count
在clicked()
回调中仅被更新一次,因此绘制的线条不会超过一条。另外,第一行是从点(glob.coordx[0], glob.coordy[0])
到(glob.coordx[0], glob.coordy[0])
(即,它在同一点开始和结束),因此它没有长度,并且将不可见。
解决方案:从glob.count = 0;
删除行do_drawing()
。
答案 1 :(得分:0)
g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);
调用回调函数时,window
(发出"button-press-event"
)将作为第一个参数传递。 queue_draw
调用队列重绘窗口。但是,不要求重绘DrawingArea
,并且不会发生。
您可以:
DrawingArea
的队列"button-press-event"
的{{1}} DrawingArea
已更改(也已调整大小)并重新绘制了此小部件。