use*_*234 3 c++ arrays colors linear-gradients
我想要做的是用彩虹渐变填充数组。该数组应包含 256 个条目,并填充颜色的十六进制值。
喜欢:
array[0] = 0xFF0000 //red
...
array[85] = 0xFFA200 //orange
...
array[170] = 0x00AF0F //green
...
array[255] = 0xAE00FF //purple
Run Code Online (Sandbox Code Playgroud)
因为我不想“手动”将所有 256 种颜色分配给我正在寻找一种动态方法的数组。它不一定是上面显示的ranbow。图片仅用于演示目的。
任何建议如何在(最好)短代码 snipit 中避免几个嵌套的 for 循环来做这样的事情?
我们要从:
红色 -> 黄色
黄色 -> 绿色
绿色 -> 青色
青色 -> 蓝色
蓝色 ->
洋红色 -> 红色。
在每次传递中,一种颜色为零,另一种颜色为 255,而最后一种颜色正在增加或减少。换句话说:
255, 0, 0 -> 255, 255, 0
255, 255, 0 -> 0, 255, 0
0 , 255, 0 -> 0, 255, 255
0 , 255, 255 -> 0, 0, 255
0 , 0, 255 -> 255, 0, 255
255, 0, 255 -> 255, 0, 0
Run Code Online (Sandbox Code Playgroud)
这可以用下面的代码,其中对于色调的范围之间进行0.0f到1.0f
//input: ratio is between 0 to 1
//output: rgb color
unsigned int rgb(double ratio)
{
//we want to normalize ratio so that it fits in to 6 regions
//where each region is 256 units long
int normalized = int(ratio * 256 * 6);
//find the distance to the start of the closest region
int x = normalized % 256;
int red = 0, grn = 0, blu = 0;
switch(normalized / 256)
{
case 0: red = 255; grn = x; blu = 0; break;//red
case 1: red = 255 - x; grn = 255; blu = 0; break;//yellow
case 2: red = 0; grn = 255; blu = x; break;//green
case 3: red = 0; grn = 255 - x; blu = 255; break;//cyan
case 4: red = x; grn = 0; blu = 255; break;//blue
case 5: red = 255; grn = 0; blu = 255 - x; break;//magenta
}
return red + (grn << 8) + (blu << 16);
}
Run Code Online (Sandbox Code Playgroud)
用法:
double range = 500;
for (double i = 0; i < range; i++)
{
unsigned int color = rgb(i / range);
...
}
Run Code Online (Sandbox Code Playgroud)
输出: