我在将颜色从 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