Using colors: redsquares.c

This page tells how to use colors. We use the module redsquares.c as an example. This module is similar to the previous one, but the squares are drawn in red, instead of white. This shows how to use colors different from black and white.

First, we have to define two variables of type XColor:

  XColor redx, reds;
We need two variables for a single color. To allocate a color, we call the function XAllocNamedColor. This can be done in any point of the program, after that the display has been opened.
  /* allocate the red color */
  XAllocNamedColor(dpy,
                     DefaultColormapOfScreen(DefaultScreenOfDisplay(dpy)),
                     "red",
                     &reds, &redx);
To change the foreground color, we call XSetForeground, passing reds.pixel as an argument. This function sets the foreground color of a graphic context.
  /* set foreground color */
  XSetForeground(dpy, g, reds.pixel);
After this, any drawing function (such as XFillRectangle) called with the graphic context g will draw in red, until the foreground color of g is changed again. Each color needs to be allocated only once, while the foreground color may be changed as many times as needed.

The module coloredsquares.c allocates an array of colors, and then choose a different color for each square.


Source code: redsquares.c, coloredsquares.c

To compile, test, and install, see: testing and installing a new module


Next: drawing characters.