How can I use the HSL colorspace in Java?

前端 未结 6 1100
遇见更好的自我
遇见更好的自我 2021-02-12 22:51

I\'ve had a look at the ColorSpace class, and found the constant TYPE_HLS (which presumably is just HSL in a different order).

Can I use this const

6条回答
  •  故里飘歌
    2021-02-12 23:18

    Here is a simple implementation that will return a Color based on hue, saturation, and lightness values from 0.0 to 1.0...

    static public Color hslColor(float h, float s, float l) {
        float q, p, r, g, b;
    
        if (s == 0) {
            r = g = b = l; // achromatic
        } else {
            q = l < 0.5 ? (l * (1 + s)) : (l + s - l * s);
            p = 2 * l - q;
            r = hue2rgb(p, q, h + 1.0f / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1.0f / 3);
        }
        return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
    }
    

    EDIT by Yona-Appletree:

    I found what I think is the correct hue2rgb function and tested it as working:

    private static float hue2rgb(float p, float q, float h) {
        if (h < 0) {
            h += 1;
        }
    
        if (h > 1) {
            h -= 1;
        }
    
        if (6 * h < 1) {
            return p + ((q - p) * 6 * h);
        }
    
        if (2 * h < 1) {
            return q;
        }
    
        if (3 * h < 2) {
            return p + ((q - p) * 6 * ((2.0f / 3.0f) - h));
        }
    
        return p;
    }
    

提交回复
热议问题