Search code examples
libgdx

How to specify a color with hue, saturation and brightness in libgdx


How to specify a color with hue, saturation and brightness in libGDX instead of r,g,b,a values. I noticed that the Color constructor only accepts rgba, at least autocompletion offered only rgba. Is this even possible? I wanted to create a gradient ranging from hue=0 to hue=255.


Solution

  • I don't think this is built into Libgdx, unless it's been added since I last checked. I made a utility method for it. This treats hue, saturation, and value as values from 0 to 1. (so pre-divide by 255 if that's the scale you're using). For hue, it circles round from red to yellow to green to cyan to blue to magenta and back to red. Or maybe in the opposite direction, forgot. I adapted the algorithm from Android's color class.

    public static Color setColor (Color target, float hue, float saturation, float value){
            saturation = MathUtils.clamp(saturation, 0.0f, 1.0f);
            hue %= 1f;
            if (hue < 0f) {
                hue++;
            }
            value = MathUtils.clamp(value, 0.0f, 1.0f);
    
            float red = 0.0f;
            float green = 0.0f;
            float blue = 0.0f;
    
            final float hf = (hue - (int) hue) * 6.0f;
            final int ihf = (int) hf;
            final float f = hf - ihf;
            final float pv = value * (1.0f - saturation);
            final float qv = value * (1.0f - saturation * f);
            final float tv = value * (1.0f - saturation * (1.0f - f));
    
            switch (ihf) {
                case 0:         // Red is the dominant color
                    red = value;
                    green = tv;
                    blue = pv;
                    break;
                case 1:         // Green is the dominant color
                    red = qv;
                    green = value;
                    blue = pv;
                    break;
                case 2:
                    red = pv;
                    green = value;
                    blue = tv;
                    break;
                case 3:         // Blue is the dominant color
                    red = pv;
                    green = qv;
                    blue = value;
                    break;
                case 4:
                    red = tv;
                    green = pv;
                    blue = value;
                    break;
                case 5:         // Red is the dominant color
                    red = value;
                    green = pv;
                    blue = qv;
                    break;
            }
    
            return target.set(red, green, blue, target.a);
        }