Skip to content

Instantly share code, notes, and snippets.

@Galeas
Last active January 2, 2016 19:09
Show Gist options
  • Save Galeas/8348748 to your computer and use it in GitHub Desktop.
Save Galeas/8348748 to your computer and use it in GitHub Desktop.
UIColor from HEX
+ (UIColor *)colorWithHex:(NSString *)hexColor
{
// Remove the hash if it exists
hexColor = [hexColor stringByReplacingOccurrencesOfString:@"#" withString:@""];
int length = (int)[hexColor length];
bool triple = (length == 3);
NSMutableArray *rgb = [[NSMutableArray alloc] init];
// Make sure the string is three or six characters long
if (triple || length == 6) {
CFIndex i = 0;
UniChar character = 0;
NSString *segment = @"";
CFStringInlineBuffer buffer;
CFStringInitInlineBuffer((__bridge CFStringRef)hexColor, &buffer, CFRangeMake(0, length));
while ((character = CFStringGetCharacterFromInlineBuffer(&buffer, i)) != 0 ) {
if (triple) segment = [segment stringByAppendingFormat:@"%c%c", character, character];
else segment = [segment stringByAppendingFormat:@"%c", character];
if ((int)[segment length] == 2) {
NSScanner *scanner = [[NSScanner alloc] initWithString:segment];
unsigned number;
while ([scanner scanHexInt:&number]) {
[rgb addObject:[NSNumber numberWithFloat:(float)(number / (float)255)]];
}
segment = @"";
}
i++;
}
// Pad the array out (for cases where we're given invalid input)
while ([rgb count] != 3) [rgb addObject:[NSNumber numberWithFloat:0.0]];
UIColor *resultColor = [UIColor colorWithRed:[[rgb objectAtIndex:0] floatValue] green:[[rgb objectAtIndex:1] floatValue] blue:[[rgb objectAtIndex:2] floatValue] alpha:1];
return resultColor;
}
else {
NSException* invalidHexException = [NSException exceptionWithName:@"InvalidHexException"
reason:@"Hex color not three or six characters excluding hash"
userInfo:nil];
@throw invalidHexException;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment