使用类别创建
.h文件
#import <UIKit/UIKit.h> @interface UIColor (HexColor) + (UIColor *)colorWithHex:(NSString *)hex; @end
.m文件
#import "UIColor+HexColor.h" @implementation UIColor (HexColor) + (UIColor *)colorWithHex:(NSString *)hex {
unsigned int red, green, blue;
NSRange range;
range.length = ; range.location = ;
if (hex.length == ) {
range.location = ;
}
[[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&red];
range.location += ;
[[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&green];
range.location += ;
[[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&blue]; return [UIColor colorWithRed:(float)(red / 255.0) green:(float)(green / 255.0) blue:(float)(blue / 255.0) alpha:1.0];
} @end
还有一个类似的方法,代码如下:
+ (UIColor *)colorWithHex:(NSString *)hex {
// Remove `#` and `0x`
if ([hex hasPrefix:@"#"]) {
hex = [hex substringFromIndex:];
} else if ([hex hasPrefix:@"0x"]) {
hex = [hex substringFromIndex:];
}
// Invalid if not 3, 6, or 8 characters
NSUInteger length = [hex length];
if (length != && length != && length != ) {
return nil;
}
// Make the string 8 characters long for easier parsing
if (length == ) {
NSString *r = [hex substringWithRange:NSMakeRange(, )];
NSString *g = [hex substringWithRange:NSMakeRange(, )];
NSString *b = [hex substringWithRange:NSMakeRange(, )];
hex = [NSString stringWithFormat:@"%@%@%@%@%@%@ff", r, r, g, g, b, b];
} else if (length == ) {
hex = [hex stringByAppendingString:@"ff"];
}
CGFloat red = [[hex substringWithRange:NSMakeRange(, )] _hexValue] / 255.0f;
CGFloat green = [[hex substringWithRange:NSMakeRange(, )] _hexValue] / 255.0f;
CGFloat blue = [[hex substringWithRange:NSMakeRange(, )] _hexValue] / 255.0f;
CGFloat alpha = [[hex substringWithRange:NSMakeRange(, )] _hexValue] / 255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; }