1
我試圖將HSL值轉換爲RGB,但是我得到了奇怪的結果,如果色相值大約爲180,那麼結果RGB是負值依賴於亮度值。將HSL轉換爲RGB的問題
我的實現:
public class HSLtoRGB {
private static float hueToRGB(float m1, float m2, float h) {
if(h < 0) {
h += 1.0f;
} else if(h > 1.0f) {
h -= 1.0f;
}
if((h * 6) < 1) {
return m1 + (m2 - m1) * 6 * h;
} else if((h * 2) < 1) {
return m2;
} else if((h * 3) < 2) {
return m1 + (m2 - m1) * ((2/3) - h) * 6;
} else {
return m1;
}
}
public static void main(String[] args) {
float h = 180.0f/360.0f;
float s = 100.0f/100.0f;
float l = 38.0f/100.0f;
float r = 0;
float g = 0;
float b = 0;
if(s == 0.0) {
r = g = b = l;
} else {
float m2 = l < 0.5 ? l * (1 + s) : (l + s) - (l * s);
float m1 = (l * 2) - m2;
r = hueToRGB(m1, m2, h + (1.0f/3.0f));
g = hueToRGB(m1, m2, h);
b = hueToRGB(m1, m2, h - (1.0f/3.0f));
}
System.out.printf("%.2f %.2f %.2f -> %.2f %.2f %.2f",
h, s, l,
r, g, b);
}
}
,並從上面的輸出:
0.50 1.00 0.38 -> 0.00 -2.28 0.76
我跟着this algorithm,並檢查其他許多人得到上面的公式,其中包括一個在CSS3文檔:
HOW TO RETURN hsl.to.rgb(h, s, l):
SELECT:
l<=0.5: PUT l*(s+1) IN m2
ELSE: PUT l+s-l*s IN m2
PUT l*2-m2 IN m1
PUT hue.to.rgb(m1, m2, h+1/3) IN r
PUT hue.to.rgb(m1, m2, h ) IN g
PUT hue.to.rgb(m1, m2, h-1/3) IN b
RETURN (r, g, b)
HOW TO RETURN hue.to.rgb(m1, m2, h):
IF h<0: PUT h+1 IN h
IF h>1: PUT h-1 IN h
IF h*6<1: RETURN m1+(m2-m1)*h*6
IF h*2<1: RETURN m2
IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6
RETURN m1
完美!謝謝你,我花了太長時間把我的頭髮脫了出來,認爲我實施了錯誤的算法... – Lerp
是的,有時候另一組眼睛就是它所需要的。樂意效勞。 – Geobits