0

I'm trying to set the scene background color to a random color on launch using the below code.

func randomColor() -> UIColor{
    //Generate between 0 to 1
    let red:CGFloat = CGFloat(drand48())
    let green:CGFloat = CGFloat(drand48())
    let blue:CGFloat = CGFloat(drand48())
    return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}

override func didMove(to view: SKView) {
    self.backgroundColor = randomColor()
    }

I'm using the code elsewhere in my program and its working as expected however when I try and set the scene background color with the same function it always loads the same green color. Any idea's why?

Sarabjit Singh
  • 1,814
  • 1
  • 17
  • 28
Mick
  • 71
  • 7

2 Answers2

2

The "standard" way to generate a random number is arc4random_uniform, not drand48 and I don't where did you find such a thing.

Instead of generating a random value for each component, why not just generate a single Int (between 0x0 and 0xffffff) and convert that to a color?

First, we generate the number:

let randomNumber = Int32(arc4random_uniform(16777216))

Next, we write an extension for UIColor that converts this number to a UIColor:

extension UIColor {
    public static func convertToColor(number: Int32) -> UIColor {
        return UIColor.init(red: CGFloat((hex>>16)&0xFF) / 255.0, green: CGFloat((hex>>8)&0xFF) / 255.0, blue: CGFloat(hex&0xFF) / 255.0, alpha: 1.0)
    }
}

Then we can call this method:

let randomColor = UIColor.convertToColor(number: randomNumber)
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

Use these below function:

 func random() -> CGFloat {
    return CGFloat(arc4random()) / CGFloat(UInt32.max)
}

func colorOfView () -> UIColor {
    return UIColor(red:   self.random(),
                   green: self.random(),
                   blue:  self.random(),
                   alpha: 1.0)
}

In comment Mukesh is right.

Reason:

Many computer color palettes and Mac output devices expect RGB color components to be representable in 8 bit values, which, when expressed as integers, are in the range of 0 to 255.

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51