2012-06-10 30 views
-2

我需要創建一個CGColor形成HTML表示形式的字符串,例如[NSColor colorWithHTMLName:]只有CoreGraphics中的手段 但如何使用HTML表示形式的字符串創建CGColor

+2

GIMME TEH CODEZ風格的問題是不被認爲是良好的。你有什麼嘗試? – 2012-06-10 17:31:55

+0

http://stackoverflow.com/questions/3010216/how-can-i-convert-rgb-hex-string-into-uicolor-in-objective-c –

回答

3

嘗試是這樣的:

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解決。

編輯:如果你不想使用基金會,嘗試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; 
} 
+0

謝謝你!從我+1,張貼純CoreGraphics解決方案作爲另一個答案 – deimus

+0

沒問題。 (我只是熟悉文檔 - 在哪裏尋找這個和那個。) – 2012-06-10 17:57:57

+0

等待 - 你不必使用基礎類。 CFStringRef與NSString橋接免費。看我的編輯。 – 2012-06-10 17:58:57

1

感謝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); 
相關問題