Generate a random UIColor
[UIColor colorWithHue:drand48() saturation:1.0 brightness:1.0 alpha:1.0];
or in Swift:
UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)
Feel free to randomise or adjust saturation and brightness to your liking.
Here is a swift version, made into a UIColor
extension:
extension UIColor {
class func randomColor(randomAlpha: Bool = false) -> UIColor {
let redValue = CGFloat(arc4random_uniform(255)) / 255.0;
let greenValue = CGFloat(arc4random_uniform(255)) / 255.0;
let blueValue = CGFloat(arc4random_uniform(255)) / 255.0;
let alphaValue = randomAlpha ? CGFloat(arc4random_uniform(255)) / 255.0 : 1;
return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: alphaValue)
}
}
Because you have assigned the colour values to int
variables. Use float
(or CGFloat
) instead. Also (as @stackunderflow's said), the remainder must
be taken modulo 256 in order to cover the whole range 0.0 ... 1.0
:
CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;