Skip to content

Instantly share code, notes, and snippets.

@ryandevore
Created July 29, 2013 18:39
Show Gist options
  • Save ryandevore/6106586 to your computer and use it in GitHub Desktop.
Save ryandevore/6106586 to your computer and use it in GitHub Desktop.
Simple category method to construct a UIColor object from a hex string.
@interface UIColor (UUColorCreation)
+ (UIColor*) uuColorFromHex:(NSString*)color;
@end
@implementation UIColor (UUColorCreation)
+ (UIColor*) uuColorFromHex:(NSString*)color
{
CGFloat rgba[4] = {0, 0, 0, 1};
if (color && (color.length == 6 || color.length == 8))
{
for (int i = 0; i < color.length; i += 2)
{
NSScanner* sc = [NSScanner scannerWithString:(NSString*)[color substringWithRange:NSMakeRange(i, 2)]];
unsigned int hex = 0;
[sc scanHexInt:&hex];
rgba[i/2] = (hex / 255.0f);
}
}
UIColor* c = [UIColor colorWithRed:rgba[0] green:rgba[1] blue:rgba[2] alpha:rgba[3]];
return c;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment