Drawing Lines
Prev | Chapter 14. The Drawing Area Widget | Next

## Drawing Lines

Drawing lines is more interesting than just points, so here is a complete program:

    #include <gtkmm/main.h>
    #include <gtkmm/window.h>
    #include <gtkmm/drawingarea.h>
    #include <gtkmm/style.h>

    //Custom drawing area with modified expose_event.
    class cust_draw_area: public Gtk::DrawingArea
    {
      int width, height;
      public:
        cust_draw_area(int x_size = 0, int y_size = 0);
        int on_expose_event(GdkEventExpose*);
    };

    //Constructor.
    cust_draw_area::cust_draw_area(int x_size, int y_size)
    : DrawingArea(), width(x_size), height(y_size)
    {
      size(width, height);
    }

    //Expose_event method.
    int cust_draw_area::on_expose_event(GdkEventExpose *event)
    {
      get_window().draw_line(this->get_style()->get_black_gc(), 5, 2, 5, 20);
      get_window().draw_line(this->get_style()->get_black_gc(), 5, 11, 10, 11);
      get_window().draw_line(this->get_style()->get_black_gc(), 10, 2, 10, 20);
      get_window().draw_line(this->get_style()->get_black_gc(), 15, 2, 21, 2);
      get_window().draw_line(this->get_style()->get_black_gc(), 18, 2, 18, 20);
      get_window().draw_line(this->get_style()->get_black_gc(), 15, 20, 21, 20);
    }

    class test_window : public Gtk::Window
    {
      cust_draw_area some_draw_area;
      public:
        test_window();
    };

    test_window::test_window()
    :  some_draw_area(50, 50)
    {
      add(some_draw_area);
      show_all();
    }

    int main(int argc, char *argv[])
    {
      Gtk::Main main_runner(argc, argv);
      test_window foo;
      main_runner.run();
      return(0);
    }

This program contains two classes. The first is a subclass of `Gtk::DrawingArea` and contains an `on_expose_event` member function. This method is called whenever the image in the drawing area needs to be redrawn. The four additional arguments to `draw_line()` (besides the graphics context as the first) are the coordinates for the start and end of the line.

The `test_window` class contains a drawing area. When it is created, it creates a drawing area of 50 pixels across by 50 pixels tall. If the window is resized, the graphic drawn is kept in the top left corner of the larger window. The drawing area is created with a default grey background.

Prev | Up | Next
Drawing Pixels | Home | Drawing Rectangles and Polygons