Search code examples
javaalgorithmcolorscycle

Going through all colors in java


I am trying to write a method of following logic:

I've got 3 integers, r, g and b.

at the beginning:

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

now as you can see, r is 255, now g should rise one by one until it reaches 255, too

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

All three integers together asseble a color. First one was red, now it's yellow. Not it should turn green, so r should decrease until only g is 255:

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

Next color should be cyan, and so on.

This is the order:

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

--> and from beginning.

I've tried to achieve this by using if-methods:

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

etc. , but i realized this is going to be long and complicated.

Does anybody has another idea of how to cycle through colors?

My goal is to change the color of a square object on each update:

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

so every time the update method is called (all 5 ms), the code gets called.

Any ideas?


Solution

  • java.awt.Color class provides a static function

    getHSBColor(float h, float s, float b)

    Use the HSB color space and make the hue component go from 0 to 1 while keeping the other components constant.

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