27

I try to get a random color for UILabel...

- (UIColor *)randomColor
{
    int red = arc4random() % 255 / 255.0;
    int green = arc4random() % 255 / 255.0;
    int blue = arc4random() % 255 / 255.0;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    NSLog(@"%@", color);
    return color;
}

And use it:

[mat addAttributes:@{NSForegroundColorAttributeName : [self randomColor]} range:range];

But color is always black. What is wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tatiana Mudryak
  • 375
  • 1
  • 3
  • 7
  • Guys please follow this link.its working perfect. http://stackoverflow.com/questions/25999303/random-color-in-ios – Mss iOS Dec 29 '16 at 13:24

10 Answers10

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

kkodev
  • 2,557
  • 23
  • 23
27

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;
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Shouldn't it be `arc4random_uniform(256) / 255.0`? Because `arc4random_uniform` returns an integer less than upper bound. So in your case r, g or b will never be 1.0 (0xFF) – ElegyD May 23 '18 at 15:29
  • @ElegyD: You are completely right, that's why I had added the final remark *"See also stackunderflow's answer about the range of possible values."* – I have edited the answer now to avoid any confusion. – Martin R May 23 '18 at 16:29
13

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)
    }
}
Bohdan Savych
  • 3,310
  • 4
  • 28
  • 47
Jbryson
  • 2,875
  • 1
  • 31
  • 53
12

Swift solution using a class var random:

extension UIColor {
    class var random: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}

Use just like any other in-built UIColor class variable (.red, .blue, .white, etc.), for example:

view.backgroundColor = .random
10623169
  • 984
  • 1
  • 12
  • 22
  • Exactly what I was looking for..! However, because it's actually making a new color every time it's called I think it'd be better as a `func random() -> UIColor` – thisIsTheFoxe Jul 31 '21 at 14:45
9

try this

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
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Jasmin
  • 794
  • 7
  • 18
6

The following works on iOS 12

NSInteger aRedValue = arc4random()%255;
NSInteger aGreenValue = arc4random()%255;
NSInteger aBlueValue = arc4random()%255;

UIColor *randColor = [UIColor colorWithRed:aRedValue/255.0f green:aGreenValue/255.0f blue:aBlueValue/255.0f alpha:1.0f];


Yogurt
  • 2,913
  • 2
  • 32
  • 63
Shankar BS
  • 8,394
  • 6
  • 41
  • 53
2
// RGB
UIColor *randomRGBColor = [[UIColor alloc] initWithRed:arc4random()%256/256.0 
                                                 green:arc4random()%256/256.0 
                                                  blue:arc4random()%256/256.0 
                                                 alpha:1.0];

// HSB
UIColor *randomHSBColor = [[UIColor alloc] initWithHue:arc4random()%256/256.0 
                                            saturation:(arc4random()%128/256.0)+0.5 
                                            brightness:(arc4random()%128/256.0)+0.5 
                                                 alpha:1.0];
se7en
  • 21
  • 3
1

arc4random() % 255 / 255.0 will always be truncated to 0 because arc4random()%255 will be an integer between 0 and 254 inclusive, and dividing by 255.0 and casting to an int will always result in 0. You should save the result as a float instead.

(Also you should use arc4random()%256 if you wish to select randomly from all possible colors.)

stackunderflow
  • 754
  • 7
  • 18
1

Here is a snippet:

CGFloat redLevel    = rand() / (float) RAND_MAX;
CGFloat greenLevel  = rand() / (float) RAND_MAX;
CGFloat blueLevel   = rand() / (float) RAND_MAX;

self.view.backgroundColor = [UIColor colorWithRed: redLevel
                                            green: greenLevel
                                             blue: blueLevel
                                            alpha: 1.0];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Jayachandra A
  • 1,335
  • 1
  • 10
  • 21
1

Removes duplication of the 3 arc4random lines :)

static func randomColor() -> UIColor {
    let random = {CGFloat(arc4random_uniform(255)) / 255.0}
    return UIColor(red: random(), green: random(), blue: random(), alpha: 1)
}
pkamb
  • 33,281
  • 23
  • 160
  • 191