diff options
Diffstat (limited to 'color.cpp')
-rw-r--r-- | color.cpp | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/color.cpp b/color.cpp new file mode 100644 index 0000000..78228a8 --- /dev/null +++ b/color.cpp | |||
@@ -0,0 +1,76 @@ | |||
1 | #include "color.h" | ||
2 | |||
3 | #include <stdio.h> | ||
4 | #include <string.h> | ||
5 | #include <ostream> | ||
6 | #include <sstream> | ||
7 | |||
8 | // Constants | ||
9 | const Color Color::White = Color(1,1,1,1); | ||
10 | const Color Color::Black = Color(0,0,0,1); | ||
11 | |||
12 | Color::Color(const unsigned char* arr) | ||
13 | { | ||
14 | float inv = 1.0 / 255.0; | ||
15 | r = arr[0] * inv; | ||
16 | g = arr[1] * inv; | ||
17 | b = arr[2] * inv; | ||
18 | a = 1.0; | ||
19 | } | ||
20 | |||
21 | Color Color::fromHex(const char* s) | ||
22 | { | ||
23 | // If the color is "none", return any color | ||
24 | // with alpha zero (completely transparent). | ||
25 | if(!strcmp(s, "none")) | ||
26 | { | ||
27 | return Color(0,0,0,0); | ||
28 | } | ||
29 | |||
30 | // Ignore leading hashmark. | ||
31 | if(s[0] == '#') | ||
32 | { | ||
33 | s++; | ||
34 | } | ||
35 | |||
36 | // Set stream formatting to hexadecimal. | ||
37 | std::stringstream ss; | ||
38 | ss << std::hex; | ||
39 | |||
40 | // Convert to integer. | ||
41 | unsigned int rgb; | ||
42 | ss << s; | ||
43 | ss >> rgb; | ||
44 | |||
45 | // Extract 8-byte chunks and normalize. | ||
46 | Color c; | ||
47 | c.r = (float)( ( rgb & 0xFF0000 ) >> 16 ) / 255.0; | ||
48 | c.g = (float)( ( rgb & 0x00FF00 ) >> 8 ) / 255.0; | ||
49 | c.b = (float)( ( rgb & 0x0000FF ) >> 0 ) / 255.0; | ||
50 | c.a = 1.0; // set alpha to 1 (opaque) by default | ||
51 | |||
52 | return c; | ||
53 | } | ||
54 | |||
55 | std::string Color::toHex() const | ||
56 | { | ||
57 | int R = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * r )); | ||
58 | int G = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * g )); | ||
59 | int B = (unsigned char) std::max( 0., std::min( 255.0, 255.0 * b )); | ||
60 | |||
61 | std::stringstream ss; | ||
62 | ss << std::hex; | ||
63 | |||
64 | ss << R << G << B; | ||
65 | return ss.str(); | ||
66 | } | ||
67 | |||
68 | std::ostream& operator<<(std::ostream& os, const Color& c) | ||
69 | { | ||
70 | os << "(r=" << c.r; | ||
71 | os << " g=" << c.g; | ||
72 | os << " b=" << c.b; | ||
73 | os << " a=" << c.a; | ||
74 | os << ")"; | ||
75 | return os; | ||
76 | } | ||