Skip to content

Instantly share code, notes, and snippets.

@amrox
Created September 30, 2010 21:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amrox/605399 to your computer and use it in GitHub Desktop.
Save amrox/605399 to your computer and use it in GitHub Desktop.
@implementation NSString (HexStuff)
- (NSUInteger)hexValue
{
NSUInteger i = 0;
// -- strip leading #
if( [self hasPrefix:@"#"] )
i++;
NSUInteger hex = 0x0;
NSInteger x;
NSString *s;
for( ; i<[self length]; ++i )
{
s = [self substringWithRange:NSMakeRange( i, 1 )];
x = [s integerValue];
NSAssert( x < 0xa, @"Something is wrong, should always be less than 10" );
if( x == 0 )
{
unichar c = [[s lowercaseString] characterAtIndex:0];
switch (c)
{
case '0':
x = 0;
break;
case 'a':
x = 0xa;
break;
case 'b':
x = 0xb;
break;
case 'c':
x = 0xc;
break;
case 'd':
x = 0xd;
break;
case 'e':
x = 0xe;
break;
case 'f':
x = 0xf;
break;
default:
return 0x0;
}
}
hex += x << 4*([self length]-i-1);
}
return hex;
}
@end
@implementation UIColor (HexStuff)
+ (UIColor *)colorWithHexString:(NSString *)string alpha:(CGFloat)alpha
{
NSInteger startIndex = 0;
CGFloat color[3] = { 0x0, 0x0, 0x0 };
if( ([string length] == 7) && [string hasPrefix:@"#"] )
{
startIndex = 1;
}
if( ([string length]-startIndex) == 6 )
{
NSString *redString = [string substringWithRange:NSMakeRange(0+startIndex, 2)];
NSString *greenString = [string substringWithRange:NSMakeRange(2+startIndex, 2)];
NSString *blueString = [string substringWithRange:NSMakeRange(4+startIndex, 2)];
color[0] = [redString hexValue];
color[1] = [greenString hexValue];
color[2] = [blueString hexValue];
}
return [UIColor colorWithRed:color[0]/0xff
green:color[1]/0xff
blue:color[2]/0xff
alpha:alpha];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment