樹心幽徑

« 20180612在GTK視窗顯示影像並偵測滑鼠按鍵位置(gtk8.c) | Main | 20180613在GTK視窗顯示縮放到和視窗同樣大小的影像(gtk9b.c) »

20180612在GTK視窗的Drawing Area顯示影像並偵測滑鼠按鍵位置(gtk9.c)
2018/06/12,22:27

(0)REF:

https://cairographics.org/tutorial/

http://zetcode.com/gfx/cairo/basicdrawing/

(1) 在GTK視窗的Drawing Area顯示影像並偵測滑鼠按鍵位置(gtk9.c)

treehrt@hrt:~/mysqlc$ cat gtk9.c
//http://zetcode.com/gfx/cairo/basicdrawing/
//resize :https://ubuntuforums.org/showthread.php?t=761973
#include <gtk/gtk.h>
#include <cairo.h>
#include <math.h>
int cx,cy;
GdkPixbuf *pix;

static gboolean on_window_draw (GtkWidget *da, GdkEvent *event, gpointer data)
{
    (void)event; (void)data;

    cairo_t *cr;
    cr = gdk_cairo_create (gtk_widget_get_window(da));
    gdk_cairo_set_source_pixbuf(cr, pix, 0, 0);
    cairo_paint(cr);
    cairo_destroy (cr);
    return TRUE;
}


static gboolean clicked(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
{
    if (event->button == 1) {
        g_print ("1:%f,%f\n", event->x, event->y);
    cx=event->x;
    cy=event->y;
        cairo_t *cr;

    cr = gdk_cairo_create (gtk_widget_get_window(widget));
 
    cairo_set_line_width(cr, 5);
    cairo_set_source_rgb(cr, 0, 1, 0);
    cairo_arc (cr, cx, cy, 10, 0, 2 * M_PI);

    cairo_stroke(cr);   
    cairo_destroy (cr);
    }

    if (event->button == 3) {
        g_print ("3:%f,%f\n", event->x, event->y);
    gtk_widget_queue_draw(widget);

    }
    return TRUE;
}


int main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *canvas;

  gtk_init (&argc, &argv);
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  GError *err = NULL;
  pix = gdk_pixbuf_new_from_file("map.png", &err);
  if(err)
    {
        printf("Error : %s\n", err->message);
        g_error_free(err);
        return FALSE;
    }
  int w=gdk_pixbuf_get_width(pix);
  int h=gdk_pixbuf_get_height(pix);
 
  canvas = gtk_drawing_area_new ();
  gtk_window_set_default_size(GTK_WINDOW(window), 100, 100);
  gtk_widget_set_size_request (canvas, w,h);
  gtk_widget_set_size_request (window, w,h);

  gtk_container_add (GTK_CONTAINER (window), canvas);
  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit) , NULL);
  g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);
  g_signal_connect (canvas, "draw", (GCallback) on_window_draw, NULL);
  gtk_widget_set_app_paintable(canvas, TRUE);

  gtk_widget_show_all (window);
  gtk_main();
  return 0;
}

 

 

(2) 編譯執行

treehrt@treehrt-BM6AE-BM1AE-BP1AE:~/mysqlc$ gcc gtk9.c -Wall `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
treehrt@treehrt-BM6AE-BM1AE-BP1AE:~/mysqlc$ ./a.out &
[15] 5774
treehrt@treehrt-BM6AE-BM1AE-BP1AE:~/mysqlc$ 3:347.677872,151.101303
3:347.677872,151.101303
3:347.677872,151.101303
3:347.677872,151.101303

 

迴響

 
Accessible and Valid XHTML 1.0 Strict and CSS Powered by LifeType