00001 #include "Color.h" 00002 00003 Color::Color(float r, float g, float b, float a):m_red(r),m_green(g),m_blue(b),m_alpha(a) { } 00004 00005 HSLColor::HSLColor(float h, float s, float l, float a):m_hue(h),m_saturation(s),m_lightness(l),m_alpha(a) { } 00006 00007 Color HSLColor::toColor() const{ 00008 return HSL2RGB(*this); 00009 } 00010 00011 void HSLColor::fromColor(const Color& color){ 00012 *this = RGB2HSL(color); 00013 } 00014 00015 HSLColor RGB2HSL(const Color& color){ 00016 float min, max, hue, saturation, lightness, alpha; 00017 00018 min = (color.red() < color.green()) ? color.red() : color.green(); 00019 min = (min < color.blue()) ? min : color.blue(); 00020 00021 max = (color.red() > color.green()) ? color.red() : color.green(); 00022 max = (max > color.blue()) ? max : color.blue(); 00023 00024 lightness = 0.5*(min + max); 00025 00026 if(max == min){ 00027 hue = 0.f; 00028 saturation = 0.f; 00029 } else { 00030 saturation = lightness < 0.5 ? (max - min)/(max + min) : (max - min)/(2.f - max - min); 00031 00032 if(max == color.red()) { 00033 hue = (color.green() - color.blue())/(max - min); 00034 } else if(max == color.green()){ 00035 hue = 2.f + (color.blue() - color.red())/(max - min); 00036 } else { 00037 hue = 4.f + (color.red() - color.green())/(max - min); 00038 } 00039 hue = hue < 0 ? hue + 6.f : hue; 00040 } 00041 00042 alpha = color.alpha(); 00043 return HSLColor(hue, saturation, lightness, alpha); 00044 } 00045 00046 Color HSL2RGB(const HSLColor& color) { 00047 float q, p, h, tc[3], col[3]; 00048 q = color.lightness() < 0.5 ? color.lightness() * (1.f + color.saturation()) : color.lightness() + color.saturation() - color.lightness() * color.saturation(); 00049 p = 2 * color.lightness() - q; 00050 h = color.hue() / 6.f; 00051 00052 tc[0] = h + 1.f/3.f; 00053 tc[1] = h; 00054 tc[2] = h - 1.f/3.f; 00055 00056 for(unsigned int i = 0; i < 3; i++){ 00057 tc[i] = tc[i] < 0 ? tc[i] + 1.f: tc[i]; 00058 tc[i] = tc[i] > 1 ? tc[i] - 1.f: tc[i]; 00059 if(6.f * tc[i] < 1.f){ 00060 col[i] = p + ((q - p) * 6.f * tc[i]); 00061 } else if(2.f * tc[i] < 1.f){ 00062 col[i] = q; 00063 } else if(3.f * tc[i] < 2.f){ 00064 col[i] = p + ((q - p) * 6.f * (2.f/3.f - tc[i])); 00065 } else { 00066 col[i] = p; 00067 } 00068 } 00069 00070 return Color(col[0], col[1], col[2], color.alpha()); 00071 } 00072 00073 std::ostream & operator<< (std::ostream& out, const Color& color){ 00074 out << "RGB(" << color.red() << ", " << color.green() << ", " << color.blue() << ")"; 00075 return out; 00076 } 00077 00078 std::ostream & operator<< (std::ostream& out, const HSLColor& color){ 00079 out << "HSL(" << color.hue() << ", " << color.saturation() << ", " << color.lightness() << ")"; 00080 return out; 00081 }