• 26 May 2013 - Since the new version attracted too many spammy registrations (around 250 fake accounts/day), user registrations are now protected by Mollom's spam protection service. Contact us if this causes some trouble.
  • 01 May 2013 - After the site upgrade, all passwords were reset and you will need to ask the site for a login reset on your first connection.

Getting (x,y) coordinates when clicking on images

I wrote an application where the user clicks on a GtkImage, and I want to know *where* the user clicked. Here's a simple object extending GtkAlignment.

I'm extending GtkAlignment, because you have to place the image in 0,0 to get the correct coordinates. Also, keep in mind that (0,0) is the top left corner of the image.

<?php
class xyGtkImage extends GtkAlignment {
    var
$eventbox;
    var
$image;  

   
    function
__construct($imagefile=NULL)
    {
       
GtkAlignment::__construct(0,0,0,0);
       
       
// create a new eventbox
       
$this->eventbox = &new GtkEventBox;
       
$this->add($this->eventbox);
       
$this->eventbox->set_events(Gdk::BUTTON_PRESS_MASK);
       
$this->eventbox->connect ('button-press-event', array($this, "print_coordinates"));
       
       
// creating the gtkimage
       
$this->image = &new GtkImage();
       
       
// if you set $imagefile then image will be automatically loaded
       
if ($imagefile !== NULL ) $this->image->set_from_file($imagefile);
       
$this->eventbox->add ($this->image);
    }
   
    function
print_coordinates($widget, $event)
    {
        echo
"You have just clicked on (" . $event->x . "," . $event->y .")\n";
    }
       
   
}
?>

Using the class is pretty simple :D

<?php

$window
= &new GtkWindow();
$window->set_position(Gtk::WIN_POS_CENTER);
$window->set_default_size (640, 480);
$window->set_title("xyGtkImage Example");
$window->connect('destroy', 'close_win');

$img = new xyGtkImage('/path/to/yourimage.png');
$window->add($img);


$window->show_all();
gtk::main();
function
close_win ()
{
   
gtk::main_quit();
}
?>