Skip to content

Instantly share code, notes, and snippets.

@fcaldarelli
Last active August 18, 2016 22:53
Show Gist options
  • Save fcaldarelli/ee6982e5b731c3acccc57da9b8ebeaa5 to your computer and use it in GitHub Desktop.
Save fcaldarelli/ee6982e5b731c3acccc57da9b8ebeaa5 to your computer and use it in GitHub Desktop.
UIColor from hex string (RGB or RGBA)
+ (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