/**
* 颜色类别
* 例如:#666777
* 例如:#666777 透明度0.1
*/
#import <UIKit/UIKit.h>
@interface UIColor (Hex)
/*
* 输入6位数返回一个颜色值
*/
+ (UIColor *)colorFromHex:(NSString *)hex;
/*
* 输入6位数返回一个颜色值
*/
+ (UIColor *)colorFromHex:(NSString *)hex alpha:(CGFloat)alpha;
@end
#import "UIColor+Hex.h"
@implementation UIColor (Hex)
+ (UIColor *)colorFromHex:(NSString *)hex
{
return [UIColor colorFromHex:hex alpha:1.0];
}
+ (UIColor *)colorFromHex:(NSString *)hex alpha:(CGFloat)alpha
{
NSString *cleanString = [hex stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6) {
cleanString = [cleanString stringByAppendingString:@"ff"];
}
unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
float red = ((baseValue >> 24) & 0xFF)/255.0f;
float green = ((baseValue >> 16) & 0xFF)/255.0f;
float blue = ((baseValue >> 8) & 0xFF)/255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end