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 o开发者_开发技巧n the algorithm?
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.
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?
Or use a Hue Saturation Value color model, and iterate over Hue.
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
HSL Color allows you to do this easily.
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);
}
精彩评论