gpt4 book ai didi

c++ - 用渐变颜色动态填充数组c++

转载 作者:行者123 更新时间:2023-11-30 01:09:18 25 4
gpt4 key购买 nike

我想要做的是用彩虹渐变填充一个数组。该数组应包含 256 个条目,并填充了颜色的十六进制值。

rainbow

喜欢:

array[0] = 0xFF0000 //red
...
array[85] = 0xFFA200 //orange
...
array[170] = 0x00AF0F //green
...
array[255] = 0xAE00FF //purple

因为我不想“手动”将所有 256 种颜色分配给数组,所以我正在为此寻找一种动态方法。它不一定需要是上面显示的 ranbow。图片仅供演示。

关于如何在(最好是)简短的代码片段中避免几个嵌套的 for 循环做这样的事情有什么建议吗?

最佳答案

我们想从:

red -> yellow
yellow -> green
green -> cyan
cyan -> blue
blue -> magenta
magenta -> red

在每一遍中,redgreenblue 组件之一始终为 0,第二个为255,第三个在0255之间递增或递减。

换句话说:

{255,  0,    0} -> {255, 255,   0} grn increases to 255
{255, 255, 0} -> { 0, 255, 0} red decreases to 0
{0 , 255, 0} -> { 0, 255, 255} blu increases to 255
{0 , 255, 255} -> { 0, 0, 255} grn decreases to 0
{0 , 0, 255} -> {255, 0, 255} red increases to 255
{255, 0, 255} -> {255, 0, 0} blu decreases to 0

这会产生 256 * 6 种颜色,我们可能不需要所有这些颜色,因此必须对其进行归一化。这可以通过以下代码完成:

//input: ratio is between 0.0 to 1.0
//output: rgb color
uint32_t 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 region for this position
int region = normalized / 256;

//find the distance to the start of the closest region
int x = normalized % 256;

uint8_t r = 0, g = 0, b = 0;
switch (region)
{
case 0: r = 255; g = 0; b = 0; g += x; break;
case 1: r = 255; g = 255; b = 0; r -= x; break;
case 2: r = 0; g = 255; b = 0; b += x; break;
case 3: r = 0; g = 255; b = 255; g -= x; break;
case 4: r = 0; g = 0; b = 255; r += x; break;
case 5: r = 255; g = 0; b = 255; b -= x; break;
}
return r + (g << 8) + (b << 16);
}

用法:

double range = 500.0;
for (double i = 0; i < range; i++)
{
uint32_t color = rgb(i / range);
...
}

输出:

enter image description here

关于c++ - 用渐变颜色动态填充数组c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40629345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com