Search code examples
iosobjective-cuicolor

Avoid light color in random UIColor


I'm generating random uicolor. I want to avoid light colors like yellow, light green etc... Here's my code

+ (UIColor *)generateRandom {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black

    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

I'm using this for uitableviewcell background color. Cell's textLabel color is white. So if the background color is light green or some other light color its not visible clearly...

How to fix this? Can we avoid generating light colors or can we find which is light color?

If we can find that is light color means I can change the textcolor to some other color...


Solution

  • It sounds like you want to avoid colors close to white. Since you're already in HSV space, this should be a simple matter of setting a distance from white to avoid. A simple implementation would limit the saturation and brightness to be no closer than some threshold. Something like:

    if (saturation < kSatThreshold)
    {
        saturation = kSatThreshold;
    }
    if (brightness > kBrightnessThreshold)
    {
        brightness = kBrightnessThreshold;
    }
    

    Something more sophisticated would be to check the distance from white and if it's too close, push it back out:

    CGFloat deltaH = hue - kWhiteHue;
    CGFloat deltaS = saturation - kWhiteSaturation;
    CGFloat deltaB = brightness - kWhiteBrightness;
    CGFloat distance = sqrt(deltaH * deltaH + deltaS * deltaS + deltaB * deltaB);
    if (distance < kDistanceThreshold)
    {
        // normalize distance vector
        deltaH /= distance;
        deltaS /= distance;
        deltaB /= distance;
        hue = kWhiteHue + deltaH * kDistanceThreshold;
        saturation = kWhiteSaturation + deltaS * kDistanceThreshold;
        brightness = kWhiteBrightness + deltaB * kDistanceThreshold;
    }