Monday, June 21, 2010

Random Colors in Objective-C

My main focus in coding always has been doing Hello Worlds. Putting a bunch of them together to actually write a well-organized program that does something is trivial, really. HelloWorlds, on the other hand, are a bitch.

So anyway... I've been going through the different ways to get multiple pages in CocoaTouch (UIScrollView, UINavigationViewController, UITabViewController etc.). Then you can put one inside the other in lots of cool combinations. But when you're creating views programmatically, it's really helpful to have random colors so your HelloWorlds look cool. To do that, you need this ridiculously simple method:



- (UIColor *) getRandomColor {
return [UIColor colorWithRed:(random()%100)/(float)100 green:(random()%100)/(float)100 blue:(random()%100)/(float)100 alpha:1];
}

If you can simplify the math, you should. [Later] Here's a better version, based on the answer here.


- (UIColor *) getRandomColor {
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;  
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

No comments: