让我们考虑以下情况:一个函数可以生成从白色到红色、从白色到蓝色、从白色到粉色、从白色到橙色等颜色代码。颜色代码采用RGB格式,取值范围为0到255。有什么想法吗?你能给我提供伪代码或这样的算法链接吗?
看起来你需要线性插值 - 在你的情况下,是从白色插值到指定的颜色。例如,在C#中:
public IEnumerable<Color> Interpolate(Color from, Color to, int steps)
{
int range = steps-1; // Makes things a bit easier
for (int i=0; i < steps; i++)
{
// i is the proportion of the "to" colour to use.
// j is the proportion of the "from" colour to use.
int j = range - i;
int r = ((from.R * j) + (to.R * i)) / range;
int g = ((from.G * j) + (to.G * i)) / range;
int b = ((from.B * j) + (to.B * i)) / range;
yield return new Color(r, g, b);
}
}
算法:
例如,如果一个极端是(0,0,0),另一个极端是(0,255,255),那么这两种颜色中间的颜色是(0,128,128)……而在这两个值之间四分之一的颜色是(0,64,64)。
从你想要渐变的两种颜色开始,并将它们分成红色、绿色和蓝色部分。
决定你想要经过多少个“步骤”进行淡化。
将R、G和B的不同之处除以步数。现在每种颜色都有一个“步长差异”。
循环遍历每个步骤,并在每次迭代中将步长差异添加到颜色值上。最后一步是四舍五入为整数。