Search code examples
iosobjective-cuicolor

How to ensure that random UIColors are visible on a white background in iOS


I'm using this code to generate a random UIColor for UILabel text in an ios app with a white background.

  • Problem is that some of the text turns out to be invisible against the white background.
  • How would you modify the code to ensure that any color chosen would be reasonably visible on a white background.

This question is as much about colors as it is programming.

+ (UIColor *) randomColor {
    CGFloat red =  (CGFloat)arc4random()/(CGFloat)RAND_MAX;
    CGFloat blue = (CGFloat)arc4random()/(CGFloat)RAND_MAX;
    CGFloat green = (CGFloat)arc4random()/(CGFloat)RAND_MAX;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

Solution

  • What I would do is determine the "gray" level of the RGB value. If it's "too close to white", then try again.

    A formula I've used is:

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

    This gives 0 for black and 1 for white. Pick a threshold such as 0.6 or whatever works for you.

    + (UIColor *) randomColor {
        while (1) {
            CGFloat red =  (CGFloat)arc4random()/(CGFloat)RAND_MAX;
            CGFloat blue = (CGFloat)arc4random()/(CGFloat)RAND_MAX;
            CGFloat green = (CGFloat)arc4random()/(CGFloat)RAND_MAX;
            CGFloat gray = 0.299 * red + 0.587 * green + 0.114 * blue;
            if (gray < 0.6) {
                return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
            }
        }
    }