UIColor from hex string representation
any snippet to get from:
NSS开发者_如何学JAVAtring *_s = @"#000000";
to:
[UIColor blackColor];
any help is highly appreciated, just been messing around with an ugly code to do this :(
A modified version - also takes an Alpha value
#define UIColorFromRGBA(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 blue:((float)((rgbValue & 0xFF00) >> 8 ))/255.0 alpha:((float)((rgbValue & 0xFF))/255.0)]
This works for me:
#define UIColorFromRGB(rgbValue) \
[UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0x0000FF))/255.0 \
alpha:1.0]
Use it like:
UIColorFromRGB(0x4c4c4c)
I wrote a category on UIColor
that accomplishes this:
Create a new Objective-C category. In your header:
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
@interface UIColor (Hex)
+ (UIColor*)colorFromHex:(NSString*)hex;
@end
And in your implementation:
@implementation UIColor (Hex)
+ (UIColor*)colorFromHex:(NSString *)hex
{
unsigned result = 0;
NSScanner *scanner = [NSScanner scannerWithString:hex];
[scanner setScanLocation:0];
[scanner scanHexInt:&result];
return UIColorFromRGB(result);
}
@end
This assume your hex string is in the format 000000
, but you can adjust to to your needs to account for a # (change [scanner setScanLocation:0]
to [scanner setScanLocation:1]
).
精彩评论