2010-06-09 39 views
13

我有來自url數據的顏色值是這樣的,「#ff33cc」。我怎樣才能將這個值轉換成UIColor?我正在嘗試以下幾行代碼。我沒有得到baseColor1的值。看起來我應該把這個重磅炸彈拿走。還有另一種方法可以做到嗎?如何將RGB十六進制字符串轉換爲objective-c中的UIColor?

NSScanner *scanner2 = [NSScanner scannerWithString:@"#ff33cc"]; 
int baseColor1; 
[scanner2 scanHexInt:&baseColor1]; 
CGFloat red = (baseColor1 & 0xFF0000); 
[UIColor colorWithRed:red ... 
+0

根據該文件,' - (BOOL)scanHexInt:(無符號*)intValue',所以你可能要聲明'baseColor'爲'unsigned';除此之外,我喜歡progrmr的回答。 – Isaac 2010-06-09 23:11:07

回答

25

你接近,但colorWithRed:green:blue:alpha:預期值從0.0到1.0,所以你需要通過255.0f到右位,除法轉移:

CGFloat red = ((baseColor1 & 0xFF0000) >> 16)/255.0f; 
CGFloat green = ((baseColor1 & 0x00FF00) >> 8)/255.0f; 
CGFloat blue = (baseColor1 & 0x0000FF)/255.0f; 

編輯 - 也NSScanner的scanHexInt會在十六進制字符串前跳過過去的0x,但我認爲它不會跳過十六進制字符串前面的#字符。您可以加入這一行來處理:

[scanner2 setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]]; 
+0

不錯的巧妙和優雅的解決方案!幹得好! – ninehundredt 2012-10-10 15:04:25

12

我添加一個字符串替代品,因此它接受一個十六進制字符串帶或不帶#

可能全碼:

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert 
{ 
    NSString *noHashString = [stringToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the # 
    NSScanner *scanner = [NSScanner scannerWithString:noHashString]; 
    [scanner setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]]; // remove + and $ 

    unsigned hex; 
    if (![scanner scanHexInt:&hex]) return nil; 
    int r = (hex >> 16) & 0xFF; 
    int g = (hex >> 8) & 0xFF; 
    int b = (hex) & 0xFF; 

    return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:1.0f]; 
} 
+0

這很好,謝謝。但是,不在掃描器上設置'charactersToBeSkipped'已經規避了對##字符串替換的需求嗎? – devios1 2015-04-27 20:55:09

1

我在以下情況下發揮了作用: - 1)帶或不帶# 2)3和6字符長值#000以及#000000 3)如果超過6位的額外數字它忽略了額外的數字

//Function Call 
UIColor *organizationColor = [self colorWithHexString:@"#AAAAAAAAAAAAA" alpha:1]; 

//Function 
- (UIColor *)colorWithHexString:(NSString *)str_HEX alpha:(CGFloat)alpha_range{ 
    NSString *noHashString = [str_HEX stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the # 

    int red = 0; 
    int green = 0; 
    int blue = 0; 

if ([str_HEX length]<=3) 
    { 
     sscanf([noHashString UTF8String], "%01X%01X%01X", &red, &green, &blue); 
     return [UIColor colorWithRed:red/16.0 green:green/16.0 blue:blue/16.0 alpha:alpha_range]; 
    } 
else if ([str_HEX length]>7) 
    { 
     NSString *mySmallerString = [noHashString substringToIndex:6]; 
     sscanf([mySmallerString UTF8String], "%02X%02X%02X", &red, &green, &blue); 
     return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range]; 
    } 
else 
{ 
    sscanf([noHashString UTF8String], "%02X%02X%02X", &red, &green, &blue); 
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range]; 
}} 
相關問題