The GDK drawing API described here is now deprecated, in favour of Cairo. See the DrawingArea chapter for information about the Cairo API.
Gdk graphics contexts (Gdk::GC
) are a
server-side resource. They contain information that describes how
drawing is to be done. This provides for fewer arguments to the
drawing methods, and less communication between the client and the
server. The following example shows how to set up a graphics context
with a foreground color of red for drawing.
Gdk::GC some_gc; some_gc.create(get_window()); Gdk::Color some_color; Gdk::Colormap some_colormap(Gdk::Colormap::get_system()); some_color.set_red(65535); some_color.set_green(0); some_color.set_blue(0); some_colormap.alloc(some_color); some_gc.set_foreground(some_color);
The first two lines create the graphics context and assign it to the
appropriate widget. The get_window()
method is
a part of the Gtk::Widget
class, so if you put
this code into a derived widget's implementation then you can call it
just as it is, otherwise you'd use
some_widget.get_window()
.
The next two lines create the Gdk::Color
and
Gdk::Colormap
. After setting the color values
you then need to allocate the color. The system figures out what to
do in this case. The colormap contains information about how colors
can be displayed on your screen, and is able to allocate the
requested color. For example, on a display of only 256 colors the
exact color requested may not be available, so the closest color to
the one requested will be used instead. The final line sets the color
as the foreground color.
There are a number of attributes that can be set for a graphics
context. There's the foreground and background color. When drawing
lines, you can set the thickness of the line with
set_line_width()
. Whether a solid or dashed line
is drawn can be set with set_line_style()
. The
size and proportions of the dashes are set with
set_dashes
. How two lines join together, whether
round or pointed or beveled off, is set with
set_join_style()
. Other things that can be set
within a graphics context include font style, stippling and tiling
for the filling of solid polygons.
Graphics contexts are central to drawing with Gdk, because nearly all Gdk
drawing functions and many Pango functions take a
Gdk::GC
object as an argument. So although Cairo
has largely superceded many Gdk drawing functions, you're still likely to
run into Gdk::GC
objects quite often, so it's
important to know what they are and how they're used.