Search code examples
ioscocoa-touchstatusbar

How to calculate the correct Text Color for status bar programmatically?


I'm developing an iOS app where's the app's main color (and the status bar color too) can be chosen by user. Is there any function to calculate if It's better a white or black text color on status bar programmaticaly starting from a RGB or HEX color?


Solution

  • Here's what I do. In summary - get the RGB values for the color. Then calculate a grayscale value from the RGB values. Then choose the status bar style based on the grayscale.

    Step 1 - get the RGB values from a UIColor:

    UIColor *color =  // your color
    CGFloat red, green, blue, alpha;
    
    if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
    
        CGFloat white;
        if ([color getWhite:&white alpha:&alpha]) {
            red = green = blue = white;
        } else {
            NSLog(@"Uh oh, not RGB or grayscale");
        }
    }
    

    Step 2 - calculate a gray value from the RGB values:

    CGFloat gray = 0.299 * red + 0.587 * green + 0.114 * blue;
    

    Step 3 - choose the status bar style:

    UIStatusBarStyle style = gray > 0.6 ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
    

    The use of 0.6 generally works. You may want to adjust that to suit your tastes.