Make the logic of ParseHexColor more easy to understand

This also fixes the #FFFF style of color hex.
This commit is contained in:
Cheng Zhao 2016-04-02 21:11:02 +09:00
parent 8bc95fe279
commit 8c3ff97ba4

View file

@ -4,31 +4,45 @@
#include "atom/common/color_util.h" #include "atom/common/color_util.h"
#include <vector>
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
namespace atom { namespace atom {
SkColor ParseHexColor(const std::string& name) { SkColor ParseHexColor(const std::string& color_string) {
auto color = name.substr(1); // Check the string for incorrect formatting.
unsigned length = color.size(); if (color_string.empty() || color_string[0] != '#')
SkColor result = (length != 8 ? 0xFF000000 : 0x00000000); return SK_ColorWHITE;
unsigned value = 0;
if (length != 3 && length != 6 && length != 8) // Prepend FF if alpha channel is not specified.
return result; std::string source = color_string.substr(1);
for (unsigned i = 0; i < length; ++i) { if (source.size() == 3)
if (!base::IsHexDigit(color[i])) source.insert(0, "F");
return result; else if (source.size() == 6)
value <<= 4; source.insert(0, "FF");
value |= (color[i] < 'A' ? color[i] - '0' : (color[i] - 'A' + 10) & 0xF);
// Convert the string from #FFF format to #FFFFFF format.
std::string formatted_color;
if (source.size() == 4) {
for (size_t i = 0; i < 4; ++i) {
formatted_color += source[i];
formatted_color += source[i];
}
} else if (source.size() == 8) {
formatted_color = source;
} else {
return SK_ColorWHITE;
} }
if (length == 6 || length == 8) {
result |= value; // Convert the string to an integer and make sure it is in the correct value
return result; // range.
} std::vector<uint8_t> bytes;
result |= (value & 0xF00) << 12 | (value & 0xF00) << 8 if (!base::HexStringToBytes(formatted_color, &bytes))
| (value & 0xF0) << 8 | (value & 0xF0) << 4 return SK_ColorWHITE;
| (value & 0xF) << 4 | (value & 0xF);
return result; return SkColorSetARGB(bytes[0], bytes[1], bytes[2], bytes[3]);
} }
} // namespace atom } // namespace atom