Pages

Showing posts with label UIColor. Show all posts
Showing posts with label UIColor. Show all posts

Sunday, December 5, 2010

Get the RGB Color Code from hex code

Here the Code Example for getting the RGB color code from the Hex code of color.

- (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];
}

thanks