开发者

How do I check if a hex color in an NSString is light or dark in Objective C?

开发者 https://www.devze.com 2023-04-10 09:56 出处:网络
I have found answers to this question that explain how to convert an NSString hex into a UIColor (I have done this) and others explaining how to convert RGB to HSB, and others explaining how to determ

I have found answers to this question that explain how to convert an NSString hex into a UIColor (I have done this) and others explaining how to convert RGB to HSB, and others explaining how to determine lightness and darkness of RGB, but I'm wondering if there is a more direct way of figuring this out that does not involve going hex->UIColor->rgb->hsb->b. Hex->hsb, for instance? Or hex->rgb->brightness calculation?

I've got backgrounds that change color each time the view loads (hex values from XML), and I need to have the text on top change to white or black开发者_开发百科 accordingly so it'll stay legible.

Help would be much appreciated, I've been kicking this around for days now.


See Formula to determine brightness of RGB color.

Hex colors are usually RRGGBB or RRGGBBAA (alpha).

how to convert hexadecimal to RGB

To get three ints instead of a UIColor, you can modify the answer from that to:

void rgb_from_hex(char *hexstring, int *red, int *green, int *blue) {
    // convert everything after the # into a number
    long x = strtol(hexstring+1, NULL, 16);

    // extract the bytes
    *blue = x & 0xFF;
    *green = (x >> 8) & 0xFF;
    *red = (x >> 16) & 0xFF;
}

// The above function is used like this:
int main (int argc, const char * argv[])
{
    int r,g,b;
    rgb_from_hex("#123456", &r, &g, &b);
    printf("r=%d, g=%d, b=%d\n", r, g, b);
}

(The function will probably only correctly handle RGB, not RGBA.)


The maximum of the red, green, and blue components seems to determine the "brightness" of a color in the HSB sense.


In addition to the above, this is another solution, put together from others' answers here and elsewhere .

    - (BOOL)hasDkBg {    
        NSScanner* scanner = [NSScanner scannerWithString:@"BD8F60"];
        int hex;
        if ([scanner scanHexInt:&hex]) {
            // Parsing successful. We have a big int representing the 0xBD8F60 value
            int r = (hex >> 16) & 0xFF; // get the first byte
            int g = (hex >>  8) & 0xFF; // get the middle byte
            int b = (hex      ) & 0xFF; // get the last byte

            int lightness = ((r*299)+(g*587)+(b*114))/1000; //get lightness value

    if (lightness < 127) { //127 = middle of possible lightness value
        return YES;
    }
    else return NO;
}    

}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号