【问题标题】:How to create CGColor with HTML representation string如何使用 HTML 表示字符串创建 CGColor
【发布时间】:2012-06-10 17:30:01
【问题描述】:

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

【问题讨论】:

标签: iphone objective-c core-graphics quartz-graphics


【解决方案1】:

试试这样的:

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;
}

【讨论】:

  • 谢谢你!来自我的 +1,发布纯 CoreGraphics 解决方案作为另一个答案
  • 没问题。 (我只是熟悉文档——在哪里可以找到这个和那个。)
  • 等等——你不必使用 Foundation 类。 CFStringRef 与 NSString 是免费桥接的。查看我的编辑。
【解决方案2】:

感谢 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2020-05-30
    • 2011-07-26
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多