Search code examples
hexuicolor

hex color from 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.


Solution

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

    You are formatting it as a digit with %d

    You want to format it as hex with %x or %X -- maybe as string %s I didnt check what the function is doing and what int hexValue is holding

    d or i Signed decimal integer 392

    x Unsigned hexadecimal integer 7fa

    X Unsigned hexadecimal integer (capital letters) 7FA