views:

44

answers:

4

I want to create a list of colors, red-yellow-green-blue, and blend into each other across a span of 100. Anyone have experience in this sort of thing?

Edit: Well, RGB actually. Any language will do. I just need the algorithm.

+1  A: 

3 nested loops. loop once on R from 1 to n loop once on g from 1 to n loop once on b from 1 to n

should give you 3^n or so colors -

Randy
+2  A: 

Use HSV colorspace for your colors (red is H=0, S=V=1, and blue is H=240, S=V=1), interpolate linearly over the Hue value and convert them to RGB:

http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB

mihi
+2  A: 

This should do it, giving all 16-million or so colors.

int[] colors;

for (int r = 0; i <= 255; i++)
{
    for (int g = 0; g <= 255; g++)
    {
        for (int b = 0; b <= 255; b++)
        {
            colors[] = rgb2int(r, g, b);
        }
    }
}

rgb2int(int red, int green, int blue)
{
    return (red << 16) + (green << 8) + blue;
}
Coronatus
+2  A: 

A simple nested RGB loop would not generate your red-yellow-green-blue gradient. If that is really what you specifically want then you should know a bit about the color wheel:

                    red
                     |
           magenta__ | __yellow
                    \|/
                  __/|\__
              blue   |   green
                     |
                    cyan

This is actually a HSV color wheel that works very well for understanding additive colors. According to this, you get yellow by mixing red and green. So, for your gradient:

// in javascript:
function cssColor (r, g, b) {
    return 'rgb('+r+','+g+','+b+')';
}

var colors = [];
// Start with solid red:
var r = 255;
var g = 0;
var b = 0;
// From red to yellow:
for (var g=0;g<=255;g++)  colors.push(cssColor(r,g,b));
// From yellow to green:
for (var r=255;r>=0;r--) colors.push(cssColor(r,g,b));
// From green to blue:
for (var b=0;b<=255;b++,g--)  colors.push(cssColor(r,g,b));

This give you an array of 768 colors. If you use every eighth color you should get your array of around 100 colors:

var subColors = [];
for (var i=0;i<colors.length;i++) {
    if (i%8 == 0) subColors.push(colors[i]);
}

Anyway, using this knowledge, you can get any gradient you want.

slebetman