Chapter 14. The Drawing Area Widget

## Chapter 14. The Drawing Area Widget

The DrawingArea widget is a blank X window that gives you the freedom to create any graphic you desire. Along with that freedom comes the responsibility to handle expose events on the widget. When a widget is first shown, or when it is covered and then uncovered again it needs to redraw itself. Most widgets have code to do this, but the DrawingArea does not, allowing you to write an expose event signal handler to determine how the contents of the widget will be drawn.

There are a number of methods to help you draw various objects into the widget, such as pixels, lines, rectangles, elipses, polygons, images, and text. We'll take each one in turn and give an example of its use.

## Graphics Contexts

Before getting into the actual drawing routines, some background information about graphics contexts is needed. Graphics contexts 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.

FontSelectionDialog |  | Drawing Pixels