如何使用 HTML 表示字符串创建 CGColor



我需要创建一个 CGColor 表单的 HTML 表示字符串,如 [NSColor colorWithHTMLName:]但只能通过CoreGraphics。

尝试这样的事情:

CGColorRef CGColorFromHTMLString(NSString *str)
{
    // remove the leading "#" and add a "0x" prefix
    str = [NSString stringWithFormat:@"0x%@", [str substringWithRange:NSMakeRange(1, str.length - 1)]];
    NSScanner *scanner;
    uint32_t result;
    scanner = [NSScanner scannerWithString:str];
    [scanner scanHexInt:&result];
    CGColorRef color = CGColorCreateGenericRGB(((result >> 16) & 0xff) / 255.0, ((result >> 8) & 0xff) / 255.0, ((result >> 0) & 0xff) / 255.0, 1.0);
    return color;
}

不要忘记在使用后通过调用CGColorRelease来释放结果。

编辑:如果你不想使用Foundation,请尝试CFStringRef或普通的C字符串:

CGColorRef CGColorFromHTMLString(const char *str)
{
    uint32_t result;
    sscanf(str + 1, "%x", &result);
    CGColorRef color = CGColorCreateGenericRGB(((result >> 16) & 0xff) / 255.0, ((result >> 8) & 0xff) / 255.0, ((result >> 0) & 0xff) / 255.0, 1.0);
    return color;
}

感谢 H2CO3 !

这是CoreGraphics解决方案,即没有基础类,而是Coregraphics和C++

    // Remove the preceding "#" symbol
    if (backGroundColor.find("#") != string::npos) {
        backGroundColor = backGroundColor.substr(1);
    }
    unsigned int decimalValue;
    sscanf(backGroundColor.c_str(), "%x", &decimalValue); 
    printf("nstring=%s, decimalValue=%u",backGroundColor.c_str(), decimalValue);
    CGColorRef result = CGColorCreateGenericRGB(((decimalValue >> 16) & 0xff) / 255.0, ((decimalValue >> 8) & 0xff) / 255.0, ((decimalValue >> 0) & 0xff) / 255.0, 1.0);

最新更新