From 330f75e663c22e1198a92fd134865ada98c3957b Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Mon, 2 May 2016 22:57:13 -0400 Subject: Initial commit --- color.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 color.cpp (limited to 'color.cpp') diff --git a/color.cpp b/color.cpp new file mode 100644 index 0000000..78228a8 --- /dev/null +++ b/color.cpp @@ -0,0 +1,76 @@ +#include "color.h" + +#include +#include +#include +#include + +// Constants +const Color Color::White = Color(1,1,1,1); +const Color Color::Black = Color(0,0,0,1); + +Color::Color(const unsigned char* arr) +{ + float inv = 1.0 / 255.0; + r = arr[0] * inv; + g = arr[1] * inv; + b = arr[2] * inv; + a = 1.0; +} + +Color Color::fromHex(const char* s) +{ + // If the color is "none", return any color + // with alpha zero (completely transparent). + if(!strcmp(s, "none")) + { + return Color(0,0,0,0); + } + + // Ignore leading hashmark. + if(s[0] == '#') + { + s++; + } + + // Set stream formatting to hexadecimal. + std::stringstream ss; + ss << std::hex; + + // Convert to integer. + unsigned int rgb; + ss << s; + ss >> rgb; + + // Extract 8-byte chunks and normalize. + Color c; + c.r = (float)( ( rgb & 0xFF0000 ) >> 16 ) / 255.0; + c.g = (float)( ( rgb & 0x00FF00 ) >> 8 ) / 255.0; + c.b = (float)( ( rgb & 0x0000FF ) >> 0 ) / 255.0; + c.a = 1.0; // set alpha to 1 (opaque) by default + + return c; +} + +std::string Color::toHex() const +{ + int R = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * r )); + int G = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * g )); + int B = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * b )); + + std::stringstream ss; + ss << std::hex; + + ss << R << G << B; + return ss.str(); +} + +std::ostream& operator<<(std::ostream& os, const Color& c) +{ + os << "(r=" << c.r; + os << " g=" << c.g; + os << " b=" << c.b; + os << " a=" << c.a; + os << ")"; + return os; +} -- cgit 1.4.1