首页 > 代码库 > 字符串颜色值转换
字符串颜色值转换
#define ColorWithString(string) [MPUniversal colorWithString:string]
/**
* 转换字符串为UIColor
*
* @param string 字符串类型:ffffff六位,ffffffff八位,#ffffff,#ffffffff; 字符允许大小写交叉
*
* @return uicolor 参数错误时,返回黑色
*/
+ (NSUInteger)valueWithCharacher:(char)c
{
if (c >= ‘a‘ && c <= ‘f‘) return c - ‘a‘ + 10;
if (c >= ‘A‘ && c <= ‘F‘) return c - ‘A‘ + 10;
if (c >= ‘0‘ && c <= ‘9‘) return c - ‘0‘;
return 0;
}
+ (UIColor *)colorWithString:(NSString *)string;
{
if (![string isKindOfClass:[NSString class]]) {
NSLog(@"MPUniversal col orWithString: 参数错误");
return [UIColor blackColor];
}
CGFloat components[4] = {};
components[3] = 1.0f;
//if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];//if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
if ([string length] % 2 == 1) {
//去#号
string = [string substringFromIndex:1];
}
for (int i = 0; i < [string length]; i+=2) {
components[i/2] = [self valueWithCharacher:[string characterAtIndex:i]] * 16 + [self valueWithCharacher:[string characterAtIndex:i+1]];
components[i/2] = components[i/2]/255.f;
}
return [UIColor colorWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
}