Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getRandomColor but avoid dark colors: Help my algorithm

I am trying to get a random color. I have done it using brute force but this method seems overly laborious (though the distribution is pretty even):

- (UIColor *) getRandomColor {
 // GOAL: reject colors that are too dark
 float total = 3;
 float one = arc4random() % 256 / 256.0;
 total -= one;
 float two = arc4random() % 256 / 256.0;
 total -= two;
 float three = total; // UIColor will chop out-of-range nums

 NSMutableArray *threeFloats = [[[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:one], [NSNumber numberWithFloat:two], [NSNumber numberWithFloat:three], nil] autorelease];

 NSNumber *red, *green, *blue;
 red = [threeFloats objectAtIndex:arc4random() % [threeFloats count]];
 [threeFloats removeObject:red];
 green = [threeFloats objectAtIndex:arc4random() % [threeFloats count]];
 [threeFloats removeObject:green];
 blue = [threeFloats lastObject];

 return [UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:1];
}

How can it be bettered? I want an even distribution of red, green and blue and nothing too dark (otherwise I'd grab three random numbers and be done with it).

like image 633
Dan Rosenstark Avatar asked Jul 28 '10 20:07

Dan Rosenstark


2 Answers

+ (UIColor *)colorWithHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha;

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

If white is ok then do saturation like hue instead of brightness.

like image 157
drawnonward Avatar answered Sep 18 '22 15:09

drawnonward


I'd probably generate (pseudo-)random numbers for hue, saturation and lightness (or HSB), with the lightness (or brightness) limited to whatever range you find reasonable, then convert that to RGB.

like image 21
Jerry Coffin Avatar answered Sep 20 '22 15:09

Jerry Coffin