Maxime Bernard's blog

Iphone - Get UIColor from a NSString CSS format

When you have to integrate your design from a psd, things can be tricky. Especially when you have to set colors. We’re all used to set colors in hex format such as CSS but UIColor only uses RGB format.

Here is the fist solution: a macro “hexToUIColor”

#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]

Then if you just have to write:

cell.textColor = UIColorFromRGB(0x333333);

But the best way to do this, is to set colors in a plist as you do in CSS. You just add a “NSString     #123456” in your css.plist. Then, you just have to use this static method:

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert{
   NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]] uppercaseString];
  // String should be 6 or 8 characters
  if ([cString length] < 6) return [UIColor blackColor];
  // strip 0X if it appears
 if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2]; 

if ([cString length] != 6) return [UIColor blackColor];
 

// Separate into r, g, b substrings
 
NSRange range;
 

range.location = 0;
 
range.length = 2;
NSString *rString = [cString substringWithRange:range];


 
range.location = 2;
NSString *gString = [cString substringWithRange:range];

range.location = 4;
NSString *bString = [cString substringWithRange:range];

// Scan values  unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];

return [UIColor colorWithRed:((float) r / 255.0f)
               green:((float) g / 255.0f)
              blue:((float) b / 255.0f)
               alpha:1.0f];
}

Hope this saved your time as it saved mine !


  1. maximebernard posted this
To Tumblr, Love PixelUnion