5

Suppose I have a class RainbowColorsMapper with the constructor RainbowColorsMapper(int n), where n>=2. Now I want to have continuous mapping of rainbow colors from red to violet which I get using the method mapper.getColor(int number) where low values correspond to red end, and high near n to violet end. If n = 2, mapper.getColor(0) returns most left color of the spectrum (near red), and mapper.getColor(1) returns the most right color. Same with bigger n with automatic scaling.

My question: can this be done relatively easy, and if yes what are suggestions on the algorithm?

bvk256
  • 1,837
  • 3
  • 20
  • 38

6 Answers6

8

The easiest way to do this will be to work in the HSL colourspace rather than RGB. Create colours where the saturation and lightness are fixed (to 100% and 50%, i would suggest), and the hue varies between suitable endpoints (which you might need to experiment to find). Convert the HSL values to RGB using Color.getHSBColor.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
2

Remember that the colours of the rainbow are ordered according to wavelength, so basically in your model, n is somehow related to wavelength. So your question essentially boils down to mapping wavelength (n) to RGB. This is not an entirely trivial process, but for a start, you could check this question out:

Convert light frequency to RGB?

Community
  • 1
  • 1
Matt Dunn
  • 5,106
  • 6
  • 31
  • 55
0

Or use a Hue Saturation Value color model, and iterate over Hue.

Mikeb
  • 6,271
  • 3
  • 27
  • 41
0

You basically have a hue change from 0 to 300 in the colour model

How to calculate RGB from Hue you can find on Wikipedia

0

HSL Color allows you to do this easily.

camickr
  • 321,443
  • 19
  • 166
  • 288
-1
 private int r = 255;
 private int g = 0;
 private int b = 0;

 private void nextRGB() {
     if (r == 255 && g < 255 && b == 0) {
         g++;
     }
     if (g == 255 && r > 0 && b == 0) {
         r--;
     }
     if (g == 255 && b < 255 && r == 0) {
         b++;
     }
     if (b == 255 && g > 0 && r == 0) {
         g--;
     }
     if (b == 255 && r < 255 && g == 0) {
         r++;
     }
     if (r == 255 && b > 0 && g == 0) {
         b--;
     }
 }

 public Color nextColor() {
     nextRGB();
     return makeColor();
 }

 private Color makeColor() {
     return new Color(r, g, b);
 }
Peter
  • 5,728
  • 20
  • 23
  • I might be wrong, but that way there are always two fixed values, so there will be no mid-tones, right? I mean `5,230,123`for example isn't possible... – Jochen Birkle Apr 03 '14 at 15:41