2
votes

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.

3

3 Answers

8
votes

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;
}
1
votes

You can convert your float values to a NSString with this code :

float r = 0.5, g = 1.0, b = 1.0, a = 1.0;
NSString *s = [[NSString alloc] initWithFormat: @"%02x%02x%02x%02x", 
    (int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)];
NSLog(@"%@", s);
0
votes

you can manually convert the color value to hex. It is pretty easy. if you have color value say

float redValue = 0.5;

you can compute corresponding hex value as follows.

redValue*=255;
    NSString *hex = [NSString stringWithFormat:@"%02x",(int)redValue];