Added hex getter; fixed hex c'tor

This commit is contained in:
Bob Polis 2022-09-30 13:42:15 +02:00
parent 74c67103d1
commit a32504bbe8
2 changed files with 20 additions and 3 deletions

View File

@ -84,17 +84,17 @@ Color::Color(const std::string& hex) {
std::istringstream iss {hex.substr(1, 2)}; std::istringstream iss {hex.substr(1, 2)};
iss >> std::hex >> val; iss >> std::hex >> val;
_rgb.r = val / 256.0; _rgb.r = val / 255.0;
iss.str(hex.substr(3, 2)); iss.str(hex.substr(3, 2));
iss.seekg(0); iss.seekg(0);
iss >> std::hex >> val; iss >> std::hex >> val;
_rgb.g = val / 256.0; _rgb.g = val / 255.0;
iss.str(hex.substr(5, 2)); iss.str(hex.substr(5, 2));
iss.seekg(0); iss.seekg(0);
iss >> std::hex >> val; iss >> std::hex >> val;
_rgb.b = val / 256.0; _rgb.b = val / 255.0;
} }
Color& Color::operator=(const RGB& rgb) { Color& Color::operator=(const RGB& rgb) {
@ -107,3 +107,18 @@ Color& Color::operator=(const HSB& hsb) {
_rgb = tmp._rgb; _rgb = tmp._rgb;
return *this; 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<unsigned int>(round(_rgb.r * 255)) <<
static_cast<unsigned int>(round(_rgb.g * 255)) <<
static_cast<unsigned int>(round(_rgb.b * 255));
return oss.str();
}

View File

@ -23,9 +23,11 @@ class Color {
operator RGB() const { return _rgb; } operator RGB() const { return _rgb; }
operator HSB() const; operator HSB() const;
std::string hex() const;
Color& operator=(const RGB& rgb); Color& operator=(const RGB& rgb);
Color& operator=(const HSB& hsb); Color& operator=(const HSB& hsb);
Color& operator=(const std::string& hex);
private: private:
RGB _rgb; RGB _rgb;