让我们考虑以下场景:一个可以生成从白色到红色、从白色到蓝色、从白色到粉色、从白色到橙色等代码颜色的函数。
颜色代码采用 RGB 格式,值从 0 到 255。
有任何想法吗?您能给我伪代码或此类算法的链接吗?
听起来你在追求线性插值 http://en.wikipedia.org/wiki/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
s.
编辑:正如评论中所指出的,RGB 很可能不是使用线性插值的最佳域。您最好将 RGB 值转换为HSL 或 HSV http://en.wikipedia.org/wiki/HSL_color_space,并对它们进行插值。这可能很简单也可能很棘手,具体取决于您的平台。上一句中的维基百科链接提供了适当计算的公式(如果没有为您提供)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)