遍历 Java 中的所有颜色



我正在尝试编写以下逻辑的方法:

我有 3 个整数,r、g 和 b。

在开头:

r = 255;
g = 0;
b = 0;

现在如您所见,R 是 255,现在 G 应该一个接一个地上升,直到它也达到 255

r = 255;
g = 255;
b = 0;

所有三个整数一起构成一种颜色。第一个是红色的,现在是黄色的。不是它应该变成绿色,所以 r 应该减小,直到只有 g 是 255:

r = 0;
g = 255;
b = 0;

下一个颜色应该是青色,依此类推。

这是顺序:

red - yellow - green - cyan - blue - violet - red 
-

->,从头。

我试图通过使用 if 方法来实现这一点:

e.g.: if(r == 255 && g == 0) g++;

等等,但我意识到这将是漫长而复杂的。

有没有人对如何循环颜色有其他想法?

我的目标是在每次更新时更改方形对象的颜色:

public void update() {
    -->color change code here<--
    color = new Color(r, g, b, alpha);
}

因此,每次调用更新方法(全部 5 毫秒)时,都会调用代码。

有什么想法吗?

java.awt.Color类提供静态函数

getHSBColor(float h, float s, float b)

使用 HSB 色彩空间并使色调分量从 0 变为 1,同时保持其他分量不变。

color = Color.getHSBColor(hue, 1, 1);

根据您的周期,您有 6 个过渡,每个过渡由 256 个步骤进行。每个过渡都在所有三个RGB通道上工作,但以移位的方式工作。

例如,假设您从255,0,0开始,您将得到类似以下内容:

R 255 ---              / ---
                      /
  0          --- --- /
G 255   / --- --- 
       /           
  0   /              --- ---
B 255           / --- --- 
               /           
  0   --- --- /             
     R   Y   G   C   B   M   R..

由此您可以轻松看到整个周期是 6 个片段 x 256 步。在每个片段上,每个通道都可以稳定,上升或下降。同时你可以看到绿色和蓝色通道就像红色通道刚刚移动一样。

所以我们只能关注红色通道:

int redValueForStep(int step) {
  step %= 256*6; // let's make step wrap around
  int fragment = step/256; // which fragment 0-5
  int fragmentStep = step%256; // which step inside fragment 0-255
  switch (fragment) {
    case 0: case 5: 
      return 255; // first and last fragment have steady high value
    case 2: case 3:
      return 0; // fragments 2 and 3 have steady low value
    case 1: return 255-fragmentStep; // falling
    case 2: return fragmentStep; // rising
}

一旦你有红色通道,你可以很容易地计算另一个,绿色通道是红色移动前两个完整的片段,所以你加 4 来环绕(以避免出现负值):

int greenValueForStep(int step) { return redValueForStep(step+256*4); }

同样的事情也适用于蓝色通道。

这是您使用 for 循环显示的更改的示例,希望对您有所帮助!

public class rgb {
    public static void main(String[] args) {
        // establish your starting conditions
        int r, g, b;
        r = 255;
        g = 0;
        b = 0;
        // increment g by 1 until it reaches 255
        for (int i = 0; i <= 255; i++) {
            g = i;
            /* Do whatever you
             * want with this
             * color here */
        }
        // de-increment r by 1 until it's 0
        for (int i = 254; i >= 0; i--) {
            r = i;
            /* Do whatever you
             * want with this
             * color here */
        }
    }
}
for (int red=0; red<256; red++)
    for (int green=0; green<256; green++)
        for (int red=0; red<256; red++) {
        // output of every combination of all red, green and blue
        }

或者,如果您只想要 0 和 255 的值,只需将它们计数为 1,然后乘以 255 进入另一个变量。

最新更新