Powered By Blogger

Monday, April 2, 2012

UIColor using HexCode

Here is the useful method for retrieving UIColor using the HexCode in your application. So, you can use your customize colors in application development.


- (UIColor *)colorWithHexCode:(NSString *)strHexCode
{
     NSString *cString = [[strHexCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
   
     // String should be 6 or 8 characters
     if ([cString length] < 6) return [UIColor grayColor];
   
     // strip 0X if it appears
     if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
   
     if ([cString length] != 6) return [UIColor grayColor];
   
     // 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 red, green, blue;
     [[NSScanner scannerWithString:rString] scanHexInt:&red];
     [[NSScanner scannerWithString:gString] scanHexInt:&green];
     [[NSScanner scannerWithString:bString] scanHexInt:&blue];
   
     return [UIColor colorWithRed:(red / 255.0f)
                      green:(green / 255.0f)
                       blue:(blue / 255.0f)
                      alpha:1.0f];
}




Thanks and Regards,
Nilesh Prajapati
 

No comments:

Post a Comment