私人资料库
本博客大部分技术文章,均从网络搜索得来,旨在收集整理技术资料,文章版权归属原作者,由此引起的任何版权问题,与本人无关。
转自:http://www.cocoachina.com/bbs/read.php?tid=63229&page=1 

 

互联应用经常会用到html颜色值转换UIColor,比如:#FF9900,0XFF9900等颜色字符串,以下方法可以将这些字符串转换为 UIColor对象。

 

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert
{
 NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
 
 // String should be 6 or 8 characters
 if ([cString length] < 6return DEFAULT_VOID_COLOR;
 
 // strip 0X if it appears
 if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
 f ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
 if ([cString length] != 6return DEFAULT_VOID_COLOR;
 // Separate into r, g, b substrings
 NSRange range;
 range.location = 0;
 range.length = 2;
 NSString *rString = [cString substringWithRange:range];
 
 range.location = 2;
 NSString *gString = [cString substringWithRange:range];
 
 range.location = 4;
 NSString *bString = [cString substringWithRange:range];
 
 // Scan values
 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.0f)
         green:((float) g / 255.0f)
       blue:((float) b / 255.0f)
         alpha:1.0f];
}

 

posted on 2011-12-21 16:35  该显示名称已被其他用户使用  阅读(219)  评论(0编辑  收藏  举报