一派护法 十九级 |
【main.c】 #include <gtk/gtk.h>
int count = 0; gdouble mx = 0.0; gdouble my = 0.0;
gboolean draw(GtkWidget *widget, cairo_t *cr, gpointer data) { // 获取绘图区域尺寸 char str[50]; guint width = gtk_widget_get_allocated_width(widget); guint height = gtk_widget_get_allocated_height(widget); // 将整个区域填充为白色 cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); // 白色 cairo_rectangle(cr, 0, 0, width, height); cairo_fill(cr);
// 画线 cairo_set_source_rgb(cr, 1.0, 0.0, 0.0); // 红色 cairo_set_line_width(cr, 0.5); cairo_move_to(cr, 10, 10); cairo_line_to(cr, 140, 90); cairo_stroke(cr); cairo_set_source_rgb(cr, 0.0, 1.0, 0.0); // 绿色 cairo_move_to(cr, 140, 90); // 不能省略! cairo_line_to(cr, 100, 10); cairo_line_to(cr, 10, 10); cairo_stroke(cr); // 画矩形 cairo_set_source_rgb(cr, 0.0, 0.0, 1.0); // 蓝色 cairo_rectangle(cr, 10, 60, 30, 30); // 后两个参数为宽度和高度,而非终点坐标 cairo_fill(cr); // 显示文字 cairo_select_font_face(cr, "serif", CAIRO_FONT_SLANT_ITALIC, CAIRO_FONT_WEIGHT_BOLD); cairo_set_source_rgb(cr, 1.0, 0.0, 1.0); // 字体颜色 cairo_set_font_size(cr, 14); // 字体大小 cairo_move_to(cr, 52, 40); cairo_show_text(cr, "English Only"); cairo_select_font_face(cr, "Source Han Sans CN Regular", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); // 该字体支持汉字 cairo_set_source_rgb(cr, 0.5, 0.4, 0.3); cairo_move_to(cr, 82, 20); cairo_show_text(cr, "简体中文ABC"); sprintf(str, "Size: %ux%u", width, height); cairo_set_source_rgb(cr, 0.74, 0.12, 0.61); cairo_set_font_size(cr, 24); cairo_move_to(cr, 6, 120); cairo_show_text(cr, str); sprintf(str, "Count=%d", count); cairo_set_source_rgb(cr, 0.24, 0.63, 0.51); cairo_move_to(cr, 20, 150); cairo_show_text(cr, str); sprintf(str, "(%lf, %lf)", mx, my); cairo_set_source_rgb(cr, 0.07, 0.83, 0.25); cairo_move_to(cr, 200, 120); cairo_show_text(cr, str); return FALSE; }
// 单击时执行2次, 双击5次,三击8次 gboolean press(GtkWidget *widget, GdkEventButton *event, gpointer data) { count++; mx = event->x; my = event->y; gtk_widget_queue_draw(widget); // 刷新整个窗口 return FALSE; }
void activate(GtkApplication *app, gpointer data) { GtkWidget *window = gtk_application_window_new(app); gtk_window_set_title(GTK_WINDOW(window), "Drawing"); // 窗口标题 gtk_window_set_default_size(GTK_WINDOW(window), 640, 480); // 窗口大小 gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // 窗口默认居中 g_signal_connect(window, "draw", G_CALLBACK(draw), NULL); // 绘图事件函数 gtk_widget_set_app_paintable(window, TRUE); // 必须要允许绘图 g_signal_connect(window, "button_press_event", G_CALLBACK(press), NULL); // 鼠标键按下事件 gtk_widget_show_all(window); }
int main(int argc, char *argv[]) { GtkApplication *app; int status; app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE); g_signal_connect(app, "activate", G_CALLBACK(activate), NULL); status = g_application_run(G_APPLICATION(app), argc, argv); g_object_unref(app); return status; }
|