整個function內容如下,先使用NSScanner來轉換成int,不過這邊倒是遇到個問題,提供的function接受的string是要0x開頭,所以得自行拿掉"#"號,並加上"0x",這樣就可以使用了。
/*
* 轉換html色碼成rgb
*/
+(UIColor*) transferHexColorCode:(NSString*)colorCode
{
// NSLog(@"color: %@",colorCode);
/*
* 無法直接使用NSScanner *scanner2 = [NSScanner scannerWithString:colorCode];
* 要先轉換成0xFF0000這樣的型式
*/
NSString *color = [NSString stringWithFormat:@"0x%@",[colorCode substringFromIndex:1]];
NSScanner *scanner2 = [NSScanner scannerWithString:color];
[scanner2 setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]];
unsigned int baseColor;
[scanner2 scanHexInt:&baseColor];
// NSLog(@"scanner2 %@",scanner2);
// NSLog(@"int: %i",baseColor);
CGFloat red = ((baseColor & 0xFF0000) >> 16) / 255.0f;
CGFloat green = ((baseColor & 0x00FF00) >> 8) / 255.0f;
CGFloat blue = (baseColor & 0x0000FF) / 255.0f;
// NSLog(@"red: %f, green: %f, blue: %f",red,green,blue);
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
參考網址:
http://stackoverflow.com/questions/3010216/how-can-i-convert-rgb-hex-string-into-uicolor-in-objective-c
http://stackoverflow.com/questions/7360958/objective-c-html-rgb-color-not-correct-in-uicolor
沒有留言:
張貼留言