Drawing Lines

Example

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

Figure 14.1. Drawing Area - Lines

Drawing Area - Lines

Source Code

File: customdrawingarea.h

#ifndef GTKMM_EXAMPLE_DRAWINGAREALINES_H
#define GTKMM_EXAMPLE_DRAWINGAREALINES_H

#include <gtkmm.h>

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

#endif //GTKMM_EXAMPLE_DRAWINGAREALINES_H


File: testwindow.h

#ifndef GTKMM_EXAMPLE_DALTESTWIN_H
#define GTKMM_EXAMPLE_DALTESTWIN_H

#include "customdrawingarea.h"

class TestWindow : public Gtk::Window
{
public:
  TestWindow();
  
protected:
  CustomDrawingArea m_drawing_area;
};

#endif

File: customdrawingarea.cc

#include "customdrawingarea.h"

CustomDrawingArea::CustomDrawingArea(int x_size, int y_size)
  : DrawingArea()
{
  set_size_request(x_size, y_size);

  //TODO: Why do we store m_width and m_height? murrayc
}

//Expose_event method.
bool CustomDrawingArea::on_expose_event(GdkEventExpose*)
{
  Glib::RefPtr<Gdk::Window> win = get_window();
  Glib::RefPtr<Gdk::GC> gc = get_style()->get_black_gc();
  win->draw_line(gc, 5, 2, 5, 20);
  win->draw_line(gc, 5, 11, 10, 11);
  win->draw_line(gc, 10, 2, 10, 20);
  win->draw_line(gc, 15, 2, 21, 2);
  win->draw_line(gc, 18, 2, 18, 20);
  win->draw_line(gc, 15, 20, 21, 20);

  // return true to stop any further event handlers being called
  // to draw this area
  return true;
}

File: main.cc

#include "testwindow.h"

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

File: testwindow.cc

#include "testwindow.h"

TestWindow::TestWindow()
  : m_drawing_area(50, 50)
{
  add(m_drawing_area);
  show_all_children();
}

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 TestWindow 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.