Last active
August 18, 2016 22:53
-
-
Save fcaldarelli/ee6982e5b731c3acccc57da9b8ebeaa5 to your computer and use it in GitHub Desktop.
UIColor from hex string (RGB or RGBA)
This file contains hidden or 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
+ (UIColor *)colorWithHexString:(NSString *)hexWithAlphaString { | |
UIColor *c = nil; | |
unsigned long long rgbValue = 0; | |
NSScanner *scanner = [NSScanner scannerWithString:hexWithAlphaString]; | |
[scanner setScanLocation:0]; // bypass '#' character | |
[scanner scanHexLongLong:&rgbValue]; | |
if(hexWithAlphaString.length == 6) | |
{ | |
c = [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0]; | |
} | |
else if(hexWithAlphaString.length == 8) | |
{ | |
c = [UIColor colorWithRed:((rgbValue & 0xFF000000) >> 24)/255.0 green:((rgbValue & 0xFF0000) >> 16)/255.0 blue:((rgbValue & 0xFF00) >> 8)/255.0 alpha:(rgbValue & 0xFF)/255.0]; | |
} | |
return c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment