2011-09-17 79 views
2

在Objective-C xcode項目中,我有一個plist文件,其中包含十六進制顏色代碼的整數。動態我想從plist文件中使用這個顏色代碼,並將該十六進制值傳遞給下面的宏以獲取UIColor對象。將字符串中的十六進制值轉換爲hext顏色代碼

宏:我需要傳遞給這個宏

#define UIColorFromRGB(rgbValue) [UIColor \ 
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ 
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \ 
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] 

我的實際十六進制值是0xF2A80C,但它是目前在plist文件。我可以把它作爲一個字符串。在這種情況下我應該怎麼做?

在此先感謝。

你想要關於這個的任何細節?

回答

8
NSScanner *scanner = [NSScanner scannerWithString:hexString]; 
unsigned hex; 
BOOL success = [scanner scanHexInt:&hex]; 
UIColor *color = UIColorFromRGB(hex); 
+1

嗨Jano謝謝。這個解決方案爲我工作。 – durai

+0

爲什麼成功沒有在代碼中使用..? – NANNAV

+0

'if(!success)NSLog(@「你的十六進制字符串是無效的)」;'你走了! – Jano

0

這個怎麼樣:

NSString *textValue = @"0xF2A80C"; 
long long value = [textValue longLongValue]; 
UIColor *color = UIColorFromRGB(value); 

我沒有測試它。所以如果有問題請告訴我。

+0

嗨Nekto,我想你的解決方案。但它沒有奏效。它始終顯示顏色爲黑色。但Jano的解決方案爲我工作。無論如何謝謝你的建議。 – durai

+0

不客氣。 – Nekto

0

您可以使用舊的C函數strtol並以16爲基礎。

const char* cString = [myStr cStringUsingEncoding:[NSString defaultCStringEncoding]]; 
int hexValue = (int)strtol(cString, NULL, 16); 
UIColor *color = UIColorFromRGB(hexValue); 
相關問題