1 + (UIColor *)colorWithHexStr:(NSString *)hexString { 2 NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString]; 3 CGFloat alpha, red, blue, green; 4 switch ([colorString length]) { 5 case 3: // #RGB 6 alpha = 1.0f; 7 red = [self colorComponentFrom: colorString start: 0 length: 1]; 8 green = [self colorComponentFrom: colorString start: 1 length: 1]; 9 blue = [self colorComponentFrom: colorString start: 2 length: 1]; 10 break; 11 case 4: // #ARGB 12 alpha = [self colorComponentFrom: colorString start: 0 length: 1]; 13 red = [self colorComponentFrom: colorString start: 1 length: 1]; 14 green = [self colorComponentFrom: colorString start: 2 length: 1]; 15 blue = [self colorComponentFrom: colorString start: 3 length: 1]; 16 break; 17 case 6: // #RRGGBB 18 alpha = 1.0f; 19 red = [self colorComponentFrom: colorString start: 0 length: 2]; 20 green = [self colorComponentFrom: colorString start: 2 length: 2]; 21 blue = [self colorComponentFrom: colorString start: 4 length: 2]; 22 break; 23 case 8: // #AARRGGBB 24 alpha = [self colorComponentFrom: colorString start: 0 length: 2]; 25 red = [self colorComponentFrom: colorString start: 2 length: 2]; 26 green = [self colorComponentFrom: colorString start: 4 length: 2]; 27 blue = [self colorComponentFrom: colorString start: 6 length: 2]; 28 break; 29 default: 30 return nil; 31 break; 32 } 33 return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; 34 } 35 36 + (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length { 37 NSString *substring = [string substringWithRange: NSMakeRange(start, length)]; 38 NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring]; 39 unsigned hexComponent; 40 [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent]; 41 return hexComponent / 255.0; 42 }