方法1:
- (UIColor )colorWithRGBHexString:(NSString )rgbColor
{
NSString *cString = rgbColor;
//去除空格并大写
cString = [[cString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([cString length] < 6)
{
//返回默认颜色
return [UIColor redColor];
}
if ([cString hasPrefix:@”0X”])
{
cString = [cString substringFromIndex:2];
}else if ([cString hasPrefix:@”#”])
{
cString = [cString substringFromIndex:1];
}
if ([cString length] != 6)
{
//返回默认颜色
return [UIColor redColor];
}
NSRange range;
range.length = 2;
range.location = 0;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
unsigned int r,g,b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:(float)r/255.0 green:(float)g/255.0 blue:(float)b/255.0 alpha:1.0f];
}
方法2:
#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]