Monday, May 16, 2011

How to Get the RGB Color Code from hex code

- (UIColor *) RGBColorCodeWithHCode: (NSString *) Hexcode{
NSString *colorstr = [[Hexcode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([colorstr length] < 6)
return [UIColor blackColor];
// strip 0X if it appears
if ([colorstr hasPrefix:@"0X"])
colorstr = [colorstr substringFromIndex:2];
if ([colorstr length] != 6)
return [UIColor blackColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rcolorString = [colorstr substringWithRange:range];
range.location = 2;
NSString *gcolorString = [colorstr substringWithRange:range];
range.location = 4;
NSString *bcolorString = [colorstr substringWithRange:range];
// Scan values
unsigned int red, green, blue;
[[NSScanner scannerWithString: rcolorString] scanHexInt:&red];
[[NSScanner scannerWithString: gcolorString] scanHexInt:&green];
[[NSScanner scannerWithString: bcolorString] scanHexInt:&blue];

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

No comments:

Post a Comment