颜色生成功能 [英] Color generation function

查看:174
本文介绍了颜色生成功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下方案:可从白到红产生code颜色的功能,从白色到蓝色,从白色到粉红色,从白色到橙色等

Let's consider the following scenario: a function which can generate code colors from white to red, from white to blue, from white to pink, from white to orange, etc.

的颜色code是RGB格式,其值从0到255

The colors code is in RGB format with values from 0 to 255.

任何想法?你能不能给我的伪code或链接,这样的算法?

Any ideas? Can you give me the pseudocode or link to such algorithm?

推荐答案

这听起来像你线性插值后是 - 在你的情况下,从白色插值到指定的颜色。例如,在C#:<​​/ P>

It sounds like you're after linear interpolation - in your case, interpolating from white to the specified colour. For example, in 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或HSV ,做插值那些。这可能是容易或非常棘手根据您的平台。在previous一句维基百科的链接给出公式相应的计算,如果你不为你提供他们。

As noted in comments, RGB may well not be the best domain in which to use linear interpolation. You may be best off converting the from/to RGB values into HSL or HSV, and doing interpolation on those. This may be easy or tricky depending on your platform. The wikipedia link in the previous sentence gives formulae for the appropriate calculations if they're not provided for you.

这篇关于颜色生成功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆