//從十六進制字符串獲取顏色,
//color:支持@“#123456”、 @“0X123456”、 @“123456”三種格式
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
//刪除字符串中的空格
NSString *cString = [[colorstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] <6)
{
return [UIColorclearColor];
}
// strip 0X if it appears
//如果是0x開頭的,那麼截取字符串,字符串從索引爲2的位置開始,一直到末尾
if ([cString hasPrefix:@"0X"])
{
cString = [cStringsubstringFromIndex:2];
}
//如果是#開頭的,那麼截取字符串,字符串從索引爲1的位置開始,一直到末尾
if ([cString hasPrefix:@"#"])
{
cString = [cStringsubstringFromIndex:1];
}
if ([cString length] !=6)
{
return [UIColorclearColor];
}
// Separate into r, g, b substrings
NSRange range;
range.location =0;
range.length =2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location =2;
NSString *gString = [cString substringWithRange:range];
//b
range.location =4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScannerscannerWithString:rString] scanHexInt:&r];
[[NSScannerscannerWithString:gString] scanHexInt:&g];
[[NSScannerscannerWithString:bString] scanHexInt:&b];
return [UIColorcolorWithRed:((float)r /255.0f) green:((float)g /255.0f) blue:((float)b /255.0f) alpha:alpha];
}
獲取到顏色以後,畫出這種顏色的圖片
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0,0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,color.CGColor);
CGContextFillRect(context, rect);
UIImage *img =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}