Paint me a Rainbow

Use HSL instead: fix the brightness and saturation and vary the hue from 0 to 360, then convert to RGB.

HSL describes colors as they are perceived by people. RGB describes them as they are used by machines. So you can't really do anything visually pleasing directly using RGB.


You can use the HSV color space and walk across the Hue dimension.


The simplest approach is to do a linear interpolation (in RGB) between each consecutive pair in this sequence:

  • #ff0000 red
  • #ffff00 yellow
  • #00ff00 green
  • #00ffff cyan
  • #0000ff blue
  • #ff00ff magenta
  • #ff0000 back to red

This should get you pretty much the same result as sweeping through the hue values in HSV or HSL, but lets you work directly in RGB. Note that only one component changes for each interpolation, which simplifies things. Here's a Python implementation:

def rainbow():
  r, g, b = 255, 0, 0
  for g in range(256):
    yield r, g, b
  for r in range(255, -1, -1):
    yield r, g, b
  for b in range(256):
    yield r, g, b
  for g in range(255, -1, -1):
    yield r, g, b
  for r in range(256):
    yield r, g, b
  for b in range(255, -1, -1):
    yield r, g, b