让我们考虑以下场景:一个函数可以生成从白到红、从白到蓝、从白到粉、从白到橙等代码颜色。
颜色代码为 RGB 格式,值从 0 到 255。
有什么想法吗?你能给我伪代码或这种算法的链接吗?
最佳答案
听起来你在寻找 linear interpolation - 在您的情况下,从白色插值到指定的颜色。例如,在 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);
}
}
当然,除了线性插值之外,还有其他方法可以做到这一点,但这可能是最简单的。请注意,如果您有很多步骤或更大的值,这会变得很棘手,因为您需要考虑溢出的可能性。在这种情况下你应该没问题——你不太可能想要超过 256 步,最大值是 255,所以你不会接近 int
的限制。
编辑:如评论中所述,RGB 可能不是使用线性插值的最佳域。您最好将从/到 RGB 值转换为 HSL or HSV ,并对这些进行插值。这可能很容易,也可能很棘手,具体取决于您的平台。上一句中的维基百科链接提供了适当计算的公式(如果未为您提供的话)。
关于algorithm - 颜色生成函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/875270/