#include "color_parser.h" #include <cstdlib> #include "window_manager_hilog.h" namespace OHOS { namespace Rosen { namespace { constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "ColorParser"}; } bool ColorParser::Parse(const std::string& colorStr, uint32_t& colorValue) { if (colorStr.empty()) { WLOGFE("color string is empty"); return false; } if (colorStr[0] == '#') { // start with '#' std::string color = colorStr.substr(1); if (!IsValidHexString(color)) { return false; } char* ptr; colorValue = std::strtoul(color.c_str(), &ptr, 16); // convert hex string to number if (colorStr.size() == 7) { // #RRGGBB: RRGGBB -> AARRGGBB colorValue |= 0xff000000; return true; } else if (colorStr.size() == 9) { // #AARRGGBB return true; } else { // do nothing } } return false; } bool ColorParser::IsValidHexString(const std::string& colorStr) { if (colorStr.empty()) { return false; } for (char ch : colorStr) { if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) { continue; } return false; } return true;
时间: 2024-04-21 15:24:53 浏览: 8
这段代码是一个名为 "ColorParser" 的命名空间中的类。它提供了两个公共的静态成员函数:Parse和IsValidHexString。
Parse函数用于解析颜色字符串,接受一个颜色字符串作为参数,并将解析后的颜色值存储在colorValue参数中。首先,它检查颜色字符串是否为空,如果为空,则返回false。然后,它检查颜色字符串是否以 '#' 开头,如果不是,则返回false。接下来,它截取字符串中的颜色部分,并检查截取后的字符串是否是一个有效的十六进制字符串。如果不是有效的十六进制字符串,则返回false。接着,它使用std::strtoul函数将十六进制字符串转换为无符号整数,并将转换后的值存储在colorValue中。如果颜色字符串长度为7,则将colorValue的高8位设置为0xFF,以将其转换为ARGB格式。如果颜色字符串长度为9,则表示颜色字符串已经是ARGB格式。最后,如果以上条件都不满足,则返回false。
IsValidHexString函数用于检查给定的字符串是否是一个有效的十六进制字符串。它首先检查字符串是否为空,如果为空,则返回false。然后,它遍历字符串中的每个字符,并检查字符是否是0-9、a-f或A-F之间的字符。如果字符不在这个范围内,则返回false。如果所有字符都满足条件,则返回true。
这段代码还使用了一些其他的头文件和命名空间,如"color_parser.h"、<cstdlib>、"window_manager_hilog.h"等。它还定义了一个私有的constexpr HiLogLabel变量LABEL,用于日志输出。