我将颜色从HSL转换为RGB时遇到问题。我编写了以下函数:
struct RGB {
float r, g, b;
};
RGB hslToRgb( float hue, float saturation, float lightness ) {
RGB rgb1, rgbResult;
float chroma = ( 1.0 - (float) abs( 2.0 * lightness - 1.0 ) ) * saturation;
float h1 = hue / 60.0;
float x = chroma * ( 1.0 - (float) abs( (float) ( (int) h1 % 2 ) - 1.0 ) );
if ( ( 0 <= h1 ) && ( h1 < 1 ) ) {
rgb1.r = chroma;
rgb1.g = x;
rgb1.b = 0.0;
} else if ( ( 1 <= h1 ) && ( h1 < 2 ) ) {
rgb1.r = x;
rgb1.g = chroma;
rgb1.b = 0.0;
} else if ( ( 2 <= h1 ) && ( h1 < 3 ) ) {
rgb1.r = 0.0;
rgb1.g = chroma;
rgb1.b = x;
} else if ( ( 3 <= h1 ) && ( h1 < 4 ) ) {
rgb1.r = 0.0;
rgb1.g = x;
rgb1.b = chroma;
} else if ( ( 4 <= h1 ) && ( h1 < 5 ) ) {
rgb1.r = x;
rgb1.g = 0.0;
rgb1.b = chroma;
} else if ( ( 5 <= h1 ) && ( h1 < 6 ) ) {
rgb1.r = chroma;
rgb1.g = 0;
rgb1.b = x;
} else {
rgb1.r = 0.0;
rgb1.g = 0.0;
rgb1.b = 0.0;
}
float m = lightness - 0.5 * chroma;
rgbResult.r = rgb1.r + m;
rgbResult.g = rgb1.g + m;
rgbResult.b = rgb1.b + m;
return rgbResult;
}
这是它的测试:
float cHue = 0.0;
while ( cHue < 360 ) {
RGB rgb1 = hslToRgb( (int) cHue, 1.0, 0.5 ); // max on saturation and a middle value for lightness
printf( "r = %f, g = %f, b = %f\n", rgb1.r, rgb1.g, rgb1.b );
cHue += 1.0;
}
但是当我需要获得此“整数”之间的所有范围时,我只能得到1.0和0.0。
r = 1.000000, g = 0.000000, b = 1.000000
r = 1.000000, g = 0.000000, b = 1.000000
r = 1.000000, g = 0.000000, b = 1.000000
r = 1.000000, g = 0.000000, b = 0.000000
r = 1.000000, g = 0.000000, b = 0.000000
r = 1.000000, g = 0.000000, b = 0.000000
谁能帮我这个代码?
公式来自:http://en.wikipedia.org/wiki/HSL_and_HSV
最佳答案
使用浮点模fmodf
作为:
float x = chroma * ( 1.0 - (float) abs( fmodf(h1, 2.0) - 1.0 ));
关于c++ - 无法从HSL转换为RGB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13407393/