Generating a list of colors, blue through red, 0% through 100%

喜欢而已 提交于 2019-12-21 19:57:02

问题


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 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.




回答2:


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




回答3:


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;
}



回答4:


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 -



来源:https://stackoverflow.com/questions/3642430/generating-a-list-of-colors-blue-through-red-0-through-100

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!