Drawing Straight Lines
| Chapter 18. The DrawingArea Widget |

## Drawing Straight Lines

Now that we understand the basics of the Cairo graphics library, we're almost ready to start drawing. We'll start with the simplest of drawing elements: the straight line. But first you need to know a little bit about Cairo's coordinate system. The origin of the Cairo coordinate system is located in the upper-left corner of the window with positive x values to the right and positive y values going down.

| Tip

Since the Cairo graphics library was written with support for multiple output targets (the X window system, PNG images, OpenGL, etc), there is a distinction between user-space and device-space coordinates. The mapping between these two coordinate systems defaults to one-to-one so that integer values map roughly to pixels on the screen, but this setting can be adjusted if desired. Sometimes it may be useful to scale the coordinates so that the full width and height of a window both range from 0 to 1 (the 'unit square') or some other mapping that works for your application. This can be done with the `Cairo::Context::scale()` function.

### Example

In this example, we'll construct a small but fully functional gtkmm program and draw some lines into the window. The lines are drawn by creating a path and then stroking it. A path is created using the functions `Cairo::Context::move_to()` and `Cairo::Context::line_to()`. The function `move_to()` is similar to the act of lifting your pen off of the paper and placing it somewhere else -- no line is drawn between the point you were at and the point you moved to. To draw a line between two points, use the `line_to()` function.

After you've finished creating your path, you still haven't drawn anything visible yet. To make the path visible, you must use the function `stroke()` which will stroke the current path with the line width and style specified in your `Cairo::Context` object. After stroking, the current path will be cleared so that you can start on your next path.

| Tip
Many Cairo drawing functions have a `_preserve()` variant. Normally drawing functions such as `clip()`, `fill()`, or `stroke()` will clear the current path. If you use the `_preserve()` variant, the current path will be retained so that you can use the same path with the next drawing function.

Figure 18.1. Drawing Area - Lines

Source Code

File: `myarea.h` (For use with gtkmm 4)

    #ifndef GTKMM_EXAMPLE_MYAREA_H
    #define GTKMM_EXAMPLE_MYAREA_H

    #include <gtkmm/drawingarea.h>

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

    protected:
      void on_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height);
    };

    #endif // GTKMM_EXAMPLE_MYAREA_H

File: `main.cc` (For use with gtkmm 4)

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

    class ExampleWindow : public Gtk::Window
    {
    public:
      ExampleWindow();

    protected:
      MyArea m_area;
    };

    ExampleWindow::ExampleWindow()
    {
      set_title("DrawingArea");
      set_child(m_area);
    }

    int main(int argc, char** argv)
    {
      auto app = Gtk::Application::create("org.gtkmm.example");

      return app->make_window_and_run<ExampleWindow>(argc, argv);
    }

File: `myarea.cc` (For use with gtkmm 4)

    #include "myarea.h"
    #include <cairomm/context.h>

    MyArea::MyArea()
    {
      set_draw_func(sigc::mem_fun(*this, &MyArea::on_draw));
    }

    MyArea::~MyArea()
    {
    }

    void MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height)
    {
      // coordinates for the center of the window
      int xc, yc;
      xc = width / 2;
      yc = height / 2;

      cr->set_line_width(10.0);

      // draw red lines out from the center of the window
      cr->set_source_rgb(0.8, 0.0, 0.0);
      cr->move_to(0, 0);
      cr->line_to(xc, yc);
      cr->line_to(0, height);
      cr->move_to(xc, yc);
      cr->line_to(width, yc);
      cr->stroke();
    }

This program contains a single class, `MyArea`, which is a subclass of `Gtk::DrawingArea` and contains an `on_draw()` member function. This function becomes the draw function by a call to `set_draw_func()` in `MyArea`'s constructor. `on_draw()` is then called whenever the image in the drawing area needs to be redrawn. It is passed a `Cairo::RefPtr` pointer to a `Cairo::Context` that we use for the drawing. The actual drawing code sets the color we want to use for drawing by using `set_source_rgb()` which takes arguments defining the Red, Green, and Blue components of the desired color (valid values are between 0 and 1). After setting the color, we created a new path using the functions `move_to()` and `line_to()`, and then stroked this path with `stroke()`.

| Drawing with relative coordinates
In the example above we drew everything using absolute coordinates. You can also draw using relative coordinates. For a straight line, this is done with the function `Cairo::Context::rel_line_to()`.

### Line styles

In addition to drawing basic straight lines, there are a number of things that you can customize about a line. You've already seen examples of setting a line's color and width, but there are others as well.

If you've drawn a series of lines that form a path, you may want them to join together in a certain way. Cairo offers three different ways to join lines together: Miter, Bevel, and Round. These are show below:

Figure 18.2. Different join types in Cairo

The line join style is set using the function `Cairo::Context::set_line_join()`.

Line ends can have different styles as well. The default style is for the line to start and stop exactly at the destination points of the line. This is called a Butt cap. The other options are Round (uses a round ending, with the center of the circle at the end point) or Square (uses a squared ending, with the center of the square at the end point). This setting is set using the function `Cairo::Context::set_line_cap()`.

There are other things you can customize as well, including creating dashed lines and other things. For more information, see the Cairo API documentation. Dashed lines are shown in the example in the Drawing Curved Lines section.

### Drawing thin lines

If you try to draw one pixel wide lines, you may notice that the line sometimes comes up blurred and wider than it ought to be. This happens because Cairo will try to draw from the selected position, to both sides (half to each), so if you're positioned right on the intersection of the pixels, and want a one pixel wide line, Cairo will try to use half of each adjacent pixel, which isn't possible (a pixel is the smallest unit possible). This happens when the width of the line is an odd number of pixels (not just one pixel).

The trick is to position in the middle of the pixel where you want the line to be drawn, and thus guaranteeing you get the desired results. See Cairo FAQ.

Figure 18.3. Drawing Area - Thin Lines

Source Code

File: `examplewindow.h` (For use with gtkmm 4)

    #ifndef GTKMM_EXAMPLEWINDOW_H
    #define GTKMM_EXAMPLEWINDOW_H

    #include <gtkmm/window.h>
    #include <gtkmm/box.h>
    #include <gtkmm/checkbutton.h>
    #include "myarea.h"

    class ExampleWindow : public Gtk::Window
    {
    public:
      ExampleWindow();
      virtual ~ExampleWindow();

    protected:
      //Signal handlers:
      void on_button_toggled();

    private:
      Gtk::Box m_HBox;
      MyArea m_Area_Lines;
      Gtk::CheckButton m_Button_FixLines;
    };

    #endif //GTKMM_EXAMPLEWINDOW_H

File: `myarea.h` (For use with gtkmm 4)

    #ifndef GTKMM_EXAMPLE_MYAREA_H
    #define GTKMM_EXAMPLE_MYAREA_H

    #include <gtkmm/drawingarea.h>

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

      void fix_lines(bool fix = true);

    protected:
      void on_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height);

    private:
      double m_fix;
    };

    #endif // GTKMM_EXAMPLE_MYAREA_H

File: `examplewindow.cc` (For use with gtkmm 4)

    #include "examplewindow.h"

    ExampleWindow::ExampleWindow()
    : m_HBox(Gtk::Orientation::HORIZONTAL),
      m_Button_FixLines("Fix lines")
    {
      set_title("Thin lines example");

      m_HBox.append(m_Area_Lines);
      m_HBox.append(m_Button_FixLines);

      set_child(m_HBox);

      m_Button_FixLines.signal_toggled().connect(
        sigc::mem_fun(*this, &ExampleWindow::on_button_toggled));

      // Synchonize the drawing in m_Area_Lines with the state of the toggle button.
      on_button_toggled();
    }

    ExampleWindow::~ExampleWindow()
    {
    }

    void ExampleWindow::on_button_toggled()
    {
      m_Area_Lines.fix_lines(m_Button_FixLines.get_active());
    }

File: `main.cc` (For use with gtkmm 4)

    #include "examplewindow.h"
    #include <gtkmm/application.h>

    int main(int argc, char* argv[])
    {
      auto app = Gtk::Application::create("org.gtkmm.example");

      //Shows the window and returns when it is closed.
      return app->make_window_and_run<ExampleWindow>(argc, argv);
    }

File: `myarea.cc` (For use with gtkmm 4)

    #include "myarea.h"

    MyArea::MyArea()
    : m_fix (0)
    {
      set_content_width(200);
      set_content_height(100);
      set_draw_func(sigc::mem_fun(*this, &MyArea::on_draw));
    }

    MyArea::~MyArea()
    {
    }

    void MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height)
    {
      cr->set_line_width(1.0);

      // draw one line, every two pixels
      // without the 'fix', you won't notice any space between the lines,
      // since each one will occupy two pixels (width)
      for (int i = 0; i < width; i += 2)
      {
        cr->move_to(i + m_fix, 0);
        cr->line_to(i + m_fix, height);
      }

      cr->stroke();
    }

    // Toogle between both values (0 or 0.5)
    void MyArea::fix_lines(bool fix)
    {
      // to get the width right, we have to draw in the middle of the pixel
      m_fix = fix ? 0.5 : 0.0;

      // force the redraw of the image
      queue_draw();
    }

Chapter 18. The DrawingArea Widget |  | Drawing Curved Lines