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: myarea.h

#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include <gtkmm/drawingarea.h>
#include <gdkmm/colormap.h>
#include <gdkmm/window.h>

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Overridden default signal handlers:
  virtual void on_realize();
  virtual bool on_expose_event(GdkEventExpose* e);

  Glib::RefPtr<Gdk::GC> gc_;
  Gdk::Color blue_, red_;
};

#endif // GTKMM_EXAMPLE_MYAREA_H

File: main.cc

#include "myarea.h"
#include <gtkmm/main.h>
#include <gtkmm/window.h>

int main(int argc, char** argv)
{
   Gtk::Main kit(argc, argv);

   Gtk::Window win;
   win.set_title("DrawingArea");

   MyArea area;
   win.add(area);
   area.show();

   Gtk::Main::run(win);

   return 0;
}

File: myarea.cc

#include "myarea.h"

MyArea::MyArea()
{
  // get_window() would return 0 because the Gdk::Window has not yet been realized
  // So we can only allocate the colors here - the rest will happen in on_realize().
  Glib::RefPtr<Gdk::Colormap> colormap = get_default_colormap ();

  blue_ = Gdk::Color("blue");
  red_ = Gdk::Color("red");

  colormap->alloc_color(blue_);
  colormap->alloc_color(red_);
}

MyArea::~MyArea()
{
}

void MyArea::on_realize()
{
  // We need to call the base on_realize()
  Gtk::DrawingArea::on_realize();

  // Now we can allocate any additional resources we need
  Glib::RefPtr<Gdk::Window> window = get_window();
  gc_ = Gdk::GC::create(window);
  window->set_background(red_);
  window->clear();
  gc_->set_foreground(blue_);
}

bool MyArea::on_expose_event(GdkEventExpose* /* event */)
{
  // This is where we draw on the window
  Glib::RefPtr<Gdk::Window> window = get_window();
  window->clear();
  window->draw_line(gc_, 1, 1, 100, 100);
  return true;
}

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.