Added constructor for hex color strings
This commit is contained in:
parent
e037e8e5b6
commit
965117d291
@ -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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
|
||||
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;
|
||||
}
|
||||
|
@ -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 <string>
|
||||
|
||||
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;
|
||||
|
Loading…
x
Reference in New Issue
Block a user