UIColor+colorWithHex: a category to get an UIColor from a hexadecimal integer value or string
Posted: | Author: Jörn | Filed under: iOS, Objective-C | 5 Comments »I always find it really cumbersome to instantiate an UIColor object from a hexadecimal color value. To make life a bit easier I wrote this category for the UIColor class:
@interface UIColor (ColorWithHex)
+(UIColor*)colorWithHexValue:(uint)hexValue andAlpha:(float)alpha;
+(UIColor*)colorWithHexString:(NSString *)hexString andAlpha:(float)alpha;
@end
@implementation UIColor (ColorWithHex)
+(UIColor*)colorWithHexValue:(uint)hexValue andAlpha:(float)alpha {
return [UIColor
colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0
green:((float)((hexValue & 0xFF00) >> 8))/255.0
blue:((float)(hexValue & 0xFF))/255.0
alpha:alpha];
}
+(UIColor*)colorWithHexString:(NSString*)hexString andAlpha:(float)alpha {
UIColor *col;
hexString = [hexString stringByReplacingOccurrencesOfString:@"#"
withString:@"0x"];
uint hexValue;
if ([[NSScanner scannerWithString:hexString] scanHexInt:&hexValue]) {
col = [self colorWithHexValue:hexValue andAlpha:alpha];
} else {
// invalid hex string
col = [self blackColor];
}
return col;
}
@end
Because I often need to convert a hex string (e.g. from a parsed XML file) to an UIColor I added 2 methods to this category. You can now get an UIColor from a hexadecimal uint value or an NSString that can have the 3 following formats: “0xFFFFFF“, “#FFFFFF” or “FFFFFF“.
Just add this category to your project and you can use it like this:
UIColor *col1 = [UIColor colorWithHexValue:0xFFFFFF andAlpha:1.0];
UIColor *col2 = [UIColor colorWithHexString:@"0xFFFFFF" andAlpha:1.0];
You can download the category here.
Feel free to use it.
1
Markus Heidtsaid atThanks a lot.
I added some convenience methods in my code:
+(UIColor*)colorWithHexString:(NSString*)hexString {
return [self colorWithHexString:hexString andAlpha:1.0];
}
+(UIColor*)colorWithHexValue:(uint)hexValue {
return [self colorWithHexValue:hexValue andAlpha:1.0];
}
2
adminsaid atGood idea, thanks!
3
Jason Jonessaid atI put this in my project — was going to code my own but figured there was someone out there that coded the same thing (as a category). Thanks man!
4
Ross Greinkesaid atAlso go the other way:
– (NSString *) hexStringFromColor {
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
// iOS 5
if ( [self respondsToSelector: @selector(getRed:green:blue:alpha:)] ) {
[self getRed: &red green: &green blue: &blue alpha: &alpha];
}
else {
const CGFloat *components = CGColorGetComponents( [self CGColor] );
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
return [NSString stringWithFormat: @”#%02X%02X%02X”,
(int) roundf( red * 255.0 ),
(int) roundf( green * 255.0 ),
(int) roundf( blue * 255.0 )];
}
5
adminsaid atNice one, Ross! Thanks for the contribution!