How to get hexcode based on the RGB values in iPhone(iOS)

cocoa-touch, ios, uicolor

Solution

I don't think you can directly get hex string from a UIColor object. You need to get Red, Green and Blue components from the UIColor object and convert them to hex and append.

You can always create something like this

-(NSString *) UIColorToHexString:(UIColor *)uiColor{
    CGColorRef color = [uiColor CGColor];

    int numComponents = CGColorGetNumberOfComponents(color);
    int red,green,blue, alpha;
    const CGFloat *components = CGColorGetComponents(color);
    if (numComponents == 4){
        red =  (int)(components[0] * 255.0) ;
        green = (int)(components[1] * 255.0);
        blue = (int)(components[2] * 255.0);
        alpha = (int)(components[3] * 255.0);
    }else{
        red  =  (int)(components[0] * 255.0) ;
        green  =  (int)(components[0] * 255.0) ;
        blue  =  (int)(components[0] * 255.0) ;
        alpha = (int)(components[1] * 255.0);
    }

    NSString *hexString  = [NSString stringWithFormat:@"#%02x%02x%02x%02x",
                            alpha,red,green,blue];
    return hexString;
}

EDIT : in iOS 5.0 you can get red,green,blue components very easly like

CGFloat red,green,blue,alpha;
[uicolor getRed:&red green:&green blue:&blue alpha:&alpha]

so the above function can be changed to

-(NSString *) UIColorToHexString:(UIColor *)uiColor{
    CGFloat red,green,blue,alpha;
    [uiColor getRed:&red green:&green blue:&blue alpha:&alpha]

    NSString *hexString  = [NSString stringWithFormat:@"#%02x%02x%02x%02x",
                            ((int)alpha),((int)red),((int)green),((int)blue)];
    return hexString;
}

Problem

I have the values of RGBA (Red, Green, Blue, Alpha). I know that we can get the UIColor value based on these things by using `UIColor *currentColor = [UIColor colorWithRed: 1 green:1 blue:0 alpha:1];` But is there a way in which i can directly get the Hex code string of a color using the RGBA values in iOS.

Original source