GdkGC: drawing at the pixel level

This tiny example shows how to perform basic drawing functions at the GDK level in a GTK application. For this one needs to access the drawable window (GdkWindow) and graphics context (GdkGC).

* Sample published by Bob Majdak on IRC
* 2008-01-26
$w = new GtkWindow;

Gtk::events_pending() || Gdk::events_pending())

* gtkwindow is special in that the gdkwindow is easily accessible.
* On other widgets, it is not as easy to get at.
* On gtkwindow it is stored in a public property called window,
* and i like to link it to a shorter name. then we have to build this
* thing called a gdkgc from it which honestly i have no idea what it is.
$gdk = $w->window; // This is a GdkWindow
$gc = new GdkGC($gdk); // This is the graphics context

$gdk->draw_line($gc, 10, 10, 630, 470);

$iter = 0;
$iter < 1000)
$gdk->draw_point($gc, rand(1, 640), rand(1, 480));


Coding note

When writing PHP-GTK code on UNIX-type systems like Linux, you'll typically want to start them with :

#!/usr/bin/php -c/etc/gtk/php.ini

before the <?php in order to use the PHP-GTK configuration instead of the standard PHP configuration, which is usually an Apache SAPI.

What is a Graphics Context ?

In low-level graphics like GDK (similar mechanisms in Apple Quartz2D, GEM VDI, Sun XGL, Win32 GDI, X.11 Xlib), a graphics context (GdkGC) is essentially a set of parameters used by drawing primitives. It can include parameters like front color, background color, drawing mode, coordinate system, and so on.

Passing the graphics context is a way to have just one parameter to pass in function calls instead of the full set of attributes, which is doubly worthwile : at the programmer level, this is much simpler than passing multiple parameters, and at the system performance level, it avoids multiple context push/pops to pass all these parameters.