Skip to content

Instantly share code, notes, and snippets.

@leilee
Created December 19, 2018 15:18
Show Gist options
  • Save leilee/8478a7dbe3071f34272b137fa623793b to your computer and use it in GitHub Desktop.
Save leilee/8478a7dbe3071f34272b137fa623793b to your computer and use it in GitHub Desktop.
UIColor+HexString
@implementation UIColor (UPHex)
+ (instancetype)up_colorWithHexString:(NSString *)hexString {
NSString *colorString = PrepareHexString(hexString);
CGFloat r, g, b, a;
switch (colorString.length) {
case 3: // #RGB
a = 1.0;
r = IntFromHexString([colorString substringWithRange:NSMakeRange(0, 1)]) /
255.0;
g = IntFromHexString([colorString substringWithRange:NSMakeRange(1, 1)]) /
255.0;
b = IntFromHexString([colorString substringWithRange:NSMakeRange(2, 1)]) /
255.0;
break;
case 4: // #ARGB
a = IntFromHexString([colorString substringWithRange:NSMakeRange(0, 1)]) /
255.0;
r = IntFromHexString([colorString substringWithRange:NSMakeRange(1, 1)]) /
255.0;
g = IntFromHexString([colorString substringWithRange:NSMakeRange(2, 1)]) /
255.0;
b = IntFromHexString([colorString substringWithRange:NSMakeRange(3, 1)]) /
255.0;
break;
case 6: // #RRGGBB
a = 1.0;
r = IntFromHexString([colorString substringWithRange:NSMakeRange(0, 2)]) /
255.0;
g = IntFromHexString([colorString substringWithRange:NSMakeRange(2, 2)]) /
255.0;
b = IntFromHexString([colorString substringWithRange:NSMakeRange(4, 2)]) /
255.0;
break;
case 8: // #AARRGGBB
a = IntFromHexString([colorString substringWithRange:NSMakeRange(0, 2)]) /
255.0;
r = IntFromHexString([colorString substringWithRange:NSMakeRange(2, 2)]) /
255.0;
g = IntFromHexString([colorString substringWithRange:NSMakeRange(4, 2)]) /
255.0;
b = IntFromHexString([colorString substringWithRange:NSMakeRange(6, 2)]) /
255.0;
break;
default:
return nil;
}
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
NS_INLINE NSString *PrepareHexString(NSString *hexString) {
NSString *string = [[hexString
stringByTrimmingCharactersInSet:NSCharacterSet
.whitespaceAndNewlineCharacterSet]
uppercaseString];
if ([string hasPrefix:@"#"]) {
return [string substringFromIndex:1];
} else if ([string hasPrefix:@"0X"]) {
return [string substringFromIndex:2];
} else {
return string;
}
}
NS_INLINE NSUInteger IntFromHexString(NSString *string) {
uint32_t result = 0;
sscanf(string.UTF8String, "%X", &result);
return result;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment