6

我正在尝试编写函数,它可以根据给定值生成两种颜色之间的颜色。一个例子会更好地解释它..

输入 ..

X : 1
Y : 0.5
Z : 0

用户给出任何一组color:value对,然后输入一个数字(比如 0.75)。然后我必须生成按比例混合 Y 和 Z 的颜色(基于它们的值和输入值)。我正在考虑以下方法。

  • 找到围绕该值的颜色,对于 0.75,它将是 0.5 和 1。
  • 根据值以某种方式混合这两种颜色并生成新颜色。

我完全迷失了,如何生成颜色,是否有任何库。

更新:这是我正在进行的一个更大项目的一部分。可以说我们有..

1 : X
0 : Y

和用户输入,0.25

我想要点东西。。

(X*0.25 + Y*0.75)

因为它更接近 Y,这就是为什么比例更高。如果用户输入,0.5.. 输出应该是

(X*0.5 + Y*0.5)

等等。我不知道如何用 RGB 颜色做到这一点。

PS:这些问题不是特定于语言的,但我是用 Java 做的。

4

3 回答 3

6

You have to blend each color channel (red, green and blue) seperately like this:

Color x,y; //set by you
float blending;//set by you

float inverse_blending = 1 - blending;

float red =   x.getRed()   * blending   +   y.getRed()   * inverse_blending;
float green = x.getGreen() * blending   +   y.getGreen() * inverse_blending;
float blue =  x.getBlue()  * blending   +   y.getBlue()  * inverse_blending;

//note that if i pass float values they have to be in the range of 0.0-1.0 
//and not in 0-255 like the ones i get returned by the getters.
Color blended = new Color (red / 255, green / 255, blue / 255);

So far for the color example. Generally if you want a linear interpolation between two values you have to do the following:

var firstValue;
var secondValue;
var interpolation;

var interpolated =  firstValue * interpolation + 
                   secondValue * (1 - interpolation);

But since you have Color-Objects in your case, you cannot interpolate the whole object in one step, you have to interpolate each relevant value on its own. Eventually you have to interpolate the alpha-channel as well, don´t know that, since you didn´t mention it, but for completeness i include it in this answer.

于 2013-07-09T09:23:54.923 回答
4

颜色是三维空间中的一个点。使用的确切坐标取决于所谓的“颜色空间”,其中有几种:RGB、HSV 等。因此,要计算两种给定颜色之间的颜色,请在同一颜色空间中获取这两种颜色,并在它们之间的 3d 空间中计算这两种颜色之间的第三个点。

最简单的方法是对颜色空间的三个值(例如 R、G 和 B)中的每一个进行线性插值。但是更复杂的是坐标值通常不是线性的,因此您必须首先将它们线性化(例如,电视颜色是指数型的,λ 约为 2.2)。根据您的应用程序,错误地假设线性可能无论如何都可以正常工作,尤其是在起始颜色已经接近的情况下。

(如 luk2302 所述,如有必要,为 alpha 添加第四个坐标)。

于 2013-07-09T09:29:53.387 回答
3

你可以通过这样的方式来使用 Java.awt.color:

public Color mixColors(Color color1, Color color2, double percent){
      double inverse_percent = 1.0 - percent;
      int redPart = (int) (color1.getRed()*percent + color2.getRed()*inverse_percent);
      int greenPart = (int) (color1.getGreen()*percent + color2.getGreen()*inverse_percent);
      int bluePart = (int) (color1.getBlue()*percent + color2.getBlue()*inverse_percent);
      return new Color(redPart, greenPart, bluePart);
}
于 2013-07-09T09:29:39.997 回答