From a32504bbe802ff6e5b06205f7e90cd40e302f6dc Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Fri, 30 Sep 2022 13:42:15 +0200 Subject: [PATCH] Added hex getter; fixed hex c'tor --- src/Color.cpp | 21 ++++++++++++++++++--- src/Color.hpp | 2 ++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Color.cpp b/src/Color.cpp index 4fe7ce5..6829a4e 100644 --- a/src/Color.cpp +++ b/src/Color.cpp @@ -84,17 +84,17 @@ Color::Color(const std::string& hex) { std::istringstream iss {hex.substr(1, 2)}; iss >> std::hex >> val; - _rgb.r = val / 256.0; + _rgb.r = val / 255.0; iss.str(hex.substr(3, 2)); iss.seekg(0); iss >> std::hex >> val; - _rgb.g = val / 256.0; + _rgb.g = val / 255.0; iss.str(hex.substr(5, 2)); iss.seekg(0); iss >> std::hex >> val; - _rgb.b = val / 256.0; + _rgb.b = val / 255.0; } Color& Color::operator=(const RGB& rgb) { @@ -107,3 +107,18 @@ Color& Color::operator=(const HSB& hsb) { _rgb = tmp._rgb; return *this; } + +Color& Color::operator=(const std::string& hex) { + Color tmp {hex}; + _rgb = tmp._rgb; + return *this; +} + +std::string Color::hex() const { + std::ostringstream oss; + oss << '#' << std::hex << + static_cast(round(_rgb.r * 255)) << + static_cast(round(_rgb.g * 255)) << + static_cast(round(_rgb.b * 255)); + return oss.str(); +} diff --git a/src/Color.hpp b/src/Color.hpp index bf31da9..7d4fcb5 100644 --- a/src/Color.hpp +++ b/src/Color.hpp @@ -23,9 +23,11 @@ class Color { operator RGB() const { return _rgb; } operator HSB() const; + std::string hex() const; Color& operator=(const RGB& rgb); Color& operator=(const HSB& hsb); + Color& operator=(const std::string& hex); private: RGB _rgb;