【发布时间】:2012-06-10 17:30:01
【问题描述】:
我需要从 HTML 表示字符串中创建一个 CGColor,例如 [NSColor colorWithHTMLName:] 但只能通过 CoreGraphics
【问题讨论】:
-
GIMME TEH CODEZ 式的问题被认为不好。你试过什么?
标签: iphone objective-c core-graphics quartz-graphics
我需要从 HTML 表示字符串中创建一个 CGColor,例如 [NSColor colorWithHTMLName:] 但只能通过 CoreGraphics
【问题讨论】:
标签: iphone objective-c core-graphics quartz-graphics
试试这样的:
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);
【讨论】: