Friday, April 22, 2011

Set UIColor from Hex Color in iPhone

We define the HexColor in our .h file

#define HexColor(color) [UIColor
colorWithRed:((color)&0xFF)/255.0
green:((color>>8)&0xFF)/255.0
blue:((color>>16)&0xFF)/255.0
alpha:((color>>24)&0xFF)/255.0]


Then we can set the color from the hex color string

unsigned int colorValue;

[[NSScanner scannerWithString: colorString] scanHexInt: &colorValue];
UIColor *color = HexColor(colorValue);


being the colorString AARRGGBB where

AA = alpha
RR = red
GG = gren
BB = blue

Another options I've seen on the Internet


// As a C function:
UIColor* UIColorFromRGB(NSInteger rgbValue) {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
green:((float)((rgbValue & 0xFF00) >> 8))/255.0
blue:((float)(rgbValue & 0xFF))/255.0
alpha:1.0];
}



// As an Objective-C function:
- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
green:((float)((rgbValue & 0xFF00) >> 8))/255.0
blue:((float)(rgbValue & 0xFF))/255.0
alpha:1.0];
}



Cheers!

No comments:

Post a Comment