Skip to content

Instantly share code, notes, and snippets.

@holysin
Last active August 29, 2015 13:56
Show Gist options
  • Save holysin/8956156 to your computer and use it in GitHub Desktop.
Save holysin/8956156 to your computer and use it in GitHub Desktop.
@interface UIColor (fromHex)
+ (UIColor *)colorwithHexString:(NSString *)hexStr alpha:(CGFloat)alpha;
@end
@implementation UIColor (fromHex)
+ (UIColor *)colorwithHexString:(NSString *)hexStr alpha:(CGFloat)alpha;
{
//-----------------------------------------
// Convert hex string to an integer
//-----------------------------------------
unsigned int hexint = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet
characterSetWithCharactersInString:@"#"]];
[scanner scanHexInt:&hexint];
//-----------------------------------------
// Create color object, specifying alpha
//-----------------------------------------
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment