diff --git a/src/Color.cpp b/src/Color.cpp index 5a20ed0..b7bc6aa 100644 --- a/src/Color.cpp +++ b/src/Color.cpp @@ -1,14 +1,9 @@ -// -// Color.cpp -// screensaver -// -// Created by Bob Polis at 2020-10-27 -// Copyright (c) 2020 SwiftCoder. All rights reserved. -// - #include "Color.hpp" #include #include +#include +#include +#include Color::Color(const RGB& rgb) : _rgb {rgb} {} @@ -81,3 +76,23 @@ Color::operator HSB() const { hsb.b = rgb_max; return hsb; } + +Color::Color(const std::string& hex) { + if (hex[0] != '#') throw std::runtime_error {"invalid hex color - must start with '#'"}; + if (hex.size() != 7) throw std::runtime_error {"invalid hex color - must be 7 chars"}; + unsigned int val; + + std::istringstream iss {hex.substr(1, 2)}; + iss >> std::hex >> val; + _rgb.r = val / 256.0; + + iss.str(hex.substr(3, 2)); + iss.seekg(0); + iss >> std::hex >> val; + _rgb.g = val / 256.0; + + iss.str(hex.substr(5, 2)); + iss.seekg(0); + iss >> std::hex >> val; + _rgb.b = val / 256.0; +} diff --git a/src/Color.hpp b/src/Color.hpp index fd6d5e4..151dd41 100644 --- a/src/Color.hpp +++ b/src/Color.hpp @@ -1,14 +1,8 @@ -// -// Color.hpp -// screensaver -// -// Created by Bob Polis at 2020-10-27 -// Copyright (c) 2020 SwiftCoder. All rights reserved. -// - #ifndef _Color_H_ #define _Color_H_ +#include + struct RGB { double r; double g; @@ -25,6 +19,7 @@ class Color { public: Color(const RGB& rgb); Color(const HSB& hsb); + Color(const std::string& hex); operator RGB() const { return _rgb; } operator HSB() const;