@@ -51,6 +51,13 @@ class Rgb {
51
51
*/
52
52
explicit Rgb (const Hsv &hsv);
53
53
54
+ /* *
55
+ * @brief Construct an Rgb object from the provided hex value.
56
+ * @param hex Hex value to convert to RGB. The hex value should be in the
57
+ * format 0xRRGGBB.
58
+ */
59
+ explicit Rgb (const uint32_t &hex);
60
+
54
61
/* *
55
62
* @brief Assign the values of the provided Rgb object to this Rgb object.
56
63
* @param other The Rgb object to copy.
@@ -82,6 +89,12 @@ class Rgb {
82
89
* @return An HSV object containing the HSV representation.
83
90
*/
84
91
Hsv hsv () const ;
92
+
93
+ /* *
94
+ * @brief Get the hex representation of this RGB color.
95
+ * @return The hex representation of this RGB color.
96
+ */
97
+ uint32_t hex () const ;
85
98
};
86
99
87
100
/* *
@@ -163,12 +176,35 @@ class Hsv {
163
176
// for allowing easy serialization/printing of the
164
177
// Rgb
165
178
template <> struct fmt ::formatter<espp::Rgb> {
166
- template <typename ParseContext> constexpr auto parse (ParseContext &ctx) const {
167
- return ctx.begin ();
179
+ // Presentation format: 'f' - floating [0,1] (default), 'd' - integer [0,255], 'x' - hex integer.
180
+ char presentation = ' f' ;
181
+
182
+ template <typename ParseContext> constexpr auto parse (ParseContext &ctx) {
183
+ // Parse the presentation format and store it in the formatter:
184
+ auto it = ctx.begin (), end = ctx.end ();
185
+ if (it != end && (*it == ' f' || *it == ' d' || *it == ' x' ))
186
+ presentation = *it++;
187
+
188
+ // TODO: Check if reached the end of the range:
189
+ // if (it != end && *it != '}') throw format_error("invalid format");
190
+
191
+ // Return an iterator past the end of the parsed range:
192
+ return it;
168
193
}
169
194
170
195
template <typename FormatContext> auto format (espp::Rgb const &rgb, FormatContext &ctx) const {
171
- return fmt::format_to (ctx.out (), " ({}, {}, {})" , rgb.r , rgb.g , rgb.b );
196
+ switch (presentation) {
197
+ case ' f' :
198
+ return fmt::format_to (ctx.out (), " ({}, {}, {})" , rgb.r , rgb.g , rgb.b );
199
+ case ' d' :
200
+ return fmt::format_to (ctx.out (), " ({}, {}, {})" , static_cast <int >(rgb.r * 255 ),
201
+ static_cast <int >(rgb.g * 255 ), static_cast <int >(rgb.b * 255 ));
202
+ case ' x' :
203
+ return fmt::format_to (ctx.out (), " {:#08X}" , rgb.hex ());
204
+ default :
205
+ // shouldn't get here!
206
+ return fmt::format_to (ctx.out (), " ({}, {}, {})" , rgb.r , rgb.g , rgb.b );
207
+ }
172
208
}
173
209
};
174
210
0 commit comments