I'm using this code to generate a random UIColor
for UILabel
text in an ios app
with 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];
}
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];
}
}
}