Last active
August 29, 2015 14:19
-
-
Save MaximAlien/f0500e36e47df6fd4961 to your computer and use it in GitHub Desktop.
[iOS] [Objective-C] Helper method to convert hex representation of the color to UIColor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface UIColor (Hex) | |
+ (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length; | |
@end | |
@implementation UIColor (Hex) | |
+ (UIColor *)colorWithHexString:(NSString *)hex | |
{ | |
NSString *colorString = [[hex stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString]; | |
CGFloat alpha, red, blue, green; | |
switch ([colorString length]) | |
{ | |
case 3: // #RGB | |
{ | |
alpha = 1.0f; | |
red = [self colorComponentFrom:colorString start:0 length:1]; | |
green = [self colorComponentFrom:colorString start:1 length:1]; | |
blue = [self colorComponentFrom:colorString start:2 length:1]; | |
break; | |
} | |
case 4: // #ARGB | |
{ | |
alpha = [self colorComponentFrom:colorString start:0 length:1]; | |
red = [self colorComponentFrom:colorString start:1 length:1]; | |
green = [self colorComponentFrom:colorString start:2 length:1]; | |
blue = [self colorComponentFrom:colorString start:3 length:1]; | |
break; | |
} | |
case 6: // #RRGGBB | |
{ | |
alpha = 1.0f; | |
red = [self colorComponentFrom:colorString start:0 length:2]; | |
green = [self colorComponentFrom:colorString start:2 length:2]; | |
blue = [self colorComponentFrom:colorString start:4 length:2]; | |
break; | |
} | |
case 8: // #AARRGGBB | |
{ | |
alpha = [self colorComponentFrom:colorString start:0 length:2]; | |
red = [self colorComponentFrom:colorString start:2 length:2]; | |
green = [self colorComponentFrom:colorString start:4 length:2]; | |
blue = [self colorComponentFrom:colorString start:6 length:2]; | |
break; | |
} | |
default: | |
{ | |
[NSException raise:@"Invalid color value" format:@"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hex]; | |
break; | |
} | |
} | |
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; | |
} | |
+ (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length | |
{ | |
NSString *substr = [string substringWithRange: NSMakeRange(start, length)]; | |
NSString *hex = length == 2 ? substr : [NSString stringWithFormat: @"%@%@", substr, substr]; | |
unsigned hexComponent; | |
[[NSScanner scannerWithString:hex] scanHexInt:&hexComponent]; | |
return hexComponent / 255.0; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment