Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex color from uicolor

Tags:

hex

uicolor

i have a problem in converting uicolor to hex color, here what i found

CGColorRef colorref = [[Colorview_ backgroundColor] CGColor];

int numComponents = CGColorGetNumberOfComponents(colorref);

if (numComponents == 4) {
    const CGFloat *components = CGColorGetComponents(colorref);

    int hexValue = 0xFF0000*components[0] + 0xFF00*components[1] + 0xFF*components[2];

    NSString *hexString = [NSString stringWithFormat:@"#%d", hexValue];
}

this code is giving me #5576149 (for example) for hexString, us you see there are 7 digits not 6, it's not a hex color, any help will be appreciated, thx.

like image 325
Elyes Jlassi Avatar asked Apr 23 '12 17:04

Elyes Jlassi


1 Answers

The sylphos answer above doesnt work for darkGrayColor.

This works better (taken from http://softteco.blogspot.jp/2011/06/extract-hex-rgb-color-from-uicolor.html):

- (NSString *) hexFromUIColor:(UIColor *)color {
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}
like image 155
ngb Avatar answered Sep 21 '22 16:09

ngb