Chapter 9. Graphics with the g2 library

Table of Contents
Snapshot
Moving objects

The g2 library is a quick way to produce simple graphics. It is not a tool for making graphics for computer games but it is convenient for showing simple figures on the screen and producing pictures to print directly or to include in reports. The examples below are also available at /Home/guests/olsson/linux-guide/g2. To link to the g2 library you have to specify "-lg2" as option to gcc. First try out the examples as they are given and modify them later to your liking.

More information is available in the g2 manual.


Snapshot

The example below illustrates producing a snapshot both on the screen (X11) and as EPS - encapsulated postscript - at the same time. The alternative line with g2_open_PS, is meant for producing postscript on a A4 paper. For the example below you will need to "#include" stdio.h, g2.h, g2_X11.h, and g2_PS.h.

main()
{
    int id, id1, id2;

    id1 = g2_open_X11(500, 500);
    //    id2 = g2_open_PS("test.ps", g2_A4, g2_PS_land);
    id2 = g2_open_EPSF("test.ps");
    id = g2_open_vd();
    g2_attach(id, id1);
    g2_attach(id, id2);

    g2_rectangle(id, 10, 10, 290, 290);
    g2_set_font_size(id, 30);
    g2_string(id, 20, 220, "g2 text");
    g2_pen(id, 19);
    g2_set_line_width(id, 5);
    g2_rectangle(id, 50, 20, 160, 160);
    g2_pen(id, 3);
    g2_filled_circle(id, 160, 220, 40);

    printf("Press Return to exit program. ");
    getchar();
    g2_close(id);
}

Moving objects

The g2 library may also be used for following the execution of a program for debugging or visualization. To move an object we need to write over the earlier location with the background color (white) and it is also important to control the flushing of the graphics buffer. (Here you only need to "#include" g2.h and g2_X11.h.)

main()
{
    int id, i;

    id = g2_open_X11(500, 500);
    g2_set_auto_flush(id, 0);		// Disable auto flush
    for (i = 0; i < 300; i++) {
      g2_pen(id, 19);		// Colur = red
      g2_filled_rectangle(id, 20 + i, 20 + i, 150 + i, 150 + i);
      g2_flush(id);		// Flush here
      g2_pen(id, 0);		// Write over with white
      g2_filled_rectangle(id, 20 + i, 20 + i, 150 + i, 150 + i);
    }

    g2_close(id);
}

Check what happens if you skip the flush statment or if you move it to the end of the loop.