1

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...

2 Answers2

0

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;
}
user1118321
  • 25,567
  • 4
  • 55
  • 86
  • What are the values need to use for constant (like kSatThreshold) –  Feb 13 '17 at 06:29
  • That's up to you. Whatever you feel is just far enough to be readable when the background is that color and the text is white. I would just experiment and see what works. My guess would be that `kSatThreshold` should be somewhere around .25-.5 and `kBrightnessThreshold` should be around .75, but that's just a guess. – user1118321 Feb 13 '17 at 06:31
  • @user1118321 Much bettah than my lazy answah. Upvoted. –  Feb 13 '17 at 06:35
0

Light colors are those with high brightness (or lightness, luminosity...).

Generate colors with random hue and saturation, but limit the randomness of brightness to low numbers, like 0 to 0.5. Or keep the brightness constant. If you are showing the colors side by side, the aesthetic impact is usually better if you change only 2 of the 3 components in HSB (HSV, HSL)

MirekE
  • 11,515
  • 5
  • 35
  • 28