color_util.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (c) 2016 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/common/color_util.h"
  5. #include <vector>
  6. #include "base/strings/string_number_conversions.h"
  7. #include "base/strings/string_util.h"
  8. #include "base/strings/stringprintf.h"
  9. namespace atom {
  10. SkColor ParseHexColor(const std::string& color_string) {
  11. // Check the string for incorrect formatting.
  12. if (color_string.empty() || color_string[0] != '#')
  13. return SK_ColorWHITE;
  14. // Prepend FF if alpha channel is not specified.
  15. std::string source = color_string.substr(1);
  16. if (source.size() == 3)
  17. source.insert(0, "F");
  18. else if (source.size() == 6)
  19. source.insert(0, "FF");
  20. // Convert the string from #FFF format to #FFFFFF format.
  21. std::string formatted_color;
  22. if (source.size() == 4) {
  23. for (size_t i = 0; i < 4; ++i) {
  24. formatted_color += source[i];
  25. formatted_color += source[i];
  26. }
  27. } else if (source.size() == 8) {
  28. formatted_color = source;
  29. } else {
  30. return SK_ColorWHITE;
  31. }
  32. // Convert the string to an integer and make sure it is in the correct value
  33. // range.
  34. std::vector<uint8_t> bytes;
  35. if (!base::HexStringToBytes(formatted_color, &bytes))
  36. return SK_ColorWHITE;
  37. return SkColorSetARGB(bytes[0], bytes[1], bytes[2], bytes[3]);
  38. }
  39. std::string ToRGBHex(SkColor color) {
  40. return base::StringPrintf("#%02X%02X%02X", SkColorGetR(color),
  41. SkColorGetG(color), SkColorGetB(color));
  42. }
  43. } // namespace atom