Skip to content

Instantly share code, notes, and snippets.

@jdcrensh
Created August 31, 2010 04:34
Show Gist options
  • Save jdcrensh/558549 to your computer and use it in GitHub Desktop.
Save jdcrensh/558549 to your computer and use it in GitHub Desktop.
Produces UIColor snippet from any given 6-char hex color value
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
NSString *hexValue = [args stringForKey:@"hex"];
if (hexValue && [hexValue length] == 6) {
NSString *hexPart;
float red, green, blue;
for (int i=0; i<[hexValue length]; i++) {
NSString *hexPrev = (hexPart ? hexPart : @"");
NSString *hexNext = [hexValue substringWithRange:NSMakeRange(i, 1)];
hexPart = [NSString stringWithFormat:@"%@%@", hexPrev, hexNext];
if (i % 2) {
unsigned int dec;
NSScanner *scan = [NSScanner scannerWithString:hexPart];
if ([scan scanHexInt:&dec]) {
if (i==1) red = (float)dec / 255.0;
else if (i==3) green = (float)dec / 255.0;
else if (i==5) blue = (float)dec / 255.0;
}
hexPart = @"";
}
}
NSLog(@"Conversion of #%@:", hexValue);
if (red == blue && red == green)
NSLog(@"[UIColor colorWithWhite:%.3f alpha:1.0]", red);
else
NSLog(@"[UIColor colorWithRed:%.3f green:%.3f blue:%.3f alpha:1.0]", red, green, blue);
}
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment