How to make a random color with Swift

62,216

Solution 1

You're going to need a function to produce random CGFloats in the range 0 to 1:

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

Then you can use this to create a random colour:

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

If you wanted a random alpha, just create another random number for that too.

You can now assign your view's background colour like so:

self.view.backgroundColor = .random()

Solution 2

For Swift 4.2

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

For Swift 3 and above:

extension CGFloat {
    static var random: CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
    }
}

Usage:

let myColor: UIColor = .random

Solution 3

Make a function to generate random color:

func getRandomColor() -> 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)
}

Now, you can call this function whenever you need random color.

self.view.backgroundColor = getRandomColor()

Solution 4

For random solid colors you can use UIColor HSB initializer and randomize only the hue:

extension UIColor {
    static var random: UIColor {
        return .init(hue: .random(in: 0...1), saturation: 1, brightness: 1, alpha: 1)
    }
}

let color1: UIColor = .random
let color2: UIColor = .random
let color3: UIColor = .random
let color4: UIColor = .random
let color5: UIColor = .random

enter image description here

Solution 5

SwiftUI - Swift 5

import SwiftUI

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}

Usage:

let randomColor: Color = .random

Share:
62,216

Related videos on Youtube

Giovanie Rodz
Author by

Giovanie Rodz

Updated on July 08, 2022

Comments

  • Giovanie Rodz
    Giovanie Rodz almost 2 years

    How I can make a random color function using Swift?

    import UIKit
    
    class ViewController: UIViewController {
    
        var randomNumber = arc4random_uniform(20)
        var randomColor = arc4random()
    
        //Color Background randomly
        func colorBackground() {
    
            // TODO: set a random color
            view.backgroundColor = UIColor.yellow
    
        }
    }
    
  • bungdito
    bungdito almost 6 years
    here if any body want to know more about CGFLoat developer.apple.com/documentation/coregraphics/cgfloat
  • Cœur
    Cœur over 5 years
    The entropy of this code is 255*255*255, which could be weak. Better generate floating values instead of small integers. On top of that, arc4random_uniform(255) will only give values from 0 to 254, so you're biased toward darker colors.
  • famfamfam
    famfamfam over 5 years
    Hi. if i want to random in range from red -> yellow. Can u provide some suggest?
  • leogdion
    leogdion over 5 years
    Great question @famfamfam I would then (instantiate based on hue, saturation, and brightness)[developer.apple.com/documentation/uikit/uicolor/‌​1621931-init]. The hue for yellow would be the midpoint of green and red. Red is 0 and Green is 1/3. Therefore yellow would be 1/6. So let's assume you want a constant saturation and brightness and orange as your midpoint then I would do: UIColor(hue: CGFloat.random(in: 0...1.0/6.0), saturation: 1.0, brightness: 1.0, alpha: 1.0) For turquoise to be your mid-point then your hue would be: CGFloat.random(in: 1.0/6.0...1.0)
  • Leo Dabus
    Leo Dabus over 4 years
    @Cœur besides that his division is flawed because he initialized CGFloat after dividing a value in the range 0...254 / 255 which would cause to zero all results
  • Cœur
    Cœur over 4 years
    Check your screenshot: what was the probability to get your perfect yellow (second result)?
  • Leo Dabus
    Leo Dabus over 4 years
    You can fine tune the odds using integers and determining now many steps you want in the hue range
  • Cœur
    Cœur over 4 years
    I believe the odds were about 1 out of 6000 for this yellow: there aren't any rounding to Int8 being done, so you had 1 chance of 1000 to get a float smaller than 0.0005 or bigger than 0.9995. And then there are 6 edges possibles (0 0 1, 0 1 0, 0 1 1, 1 0 0, 1 0 1, 1 1 0).
  • Leo Dabus
    Leo Dabus over 4 years
    I think you are right I came up with the odds of 1 out of 6666 to generate a float in range 0.16659 ... 0.16674
  • Vyachaslav Gerchicov
    Vyachaslav Gerchicov over 3 years
    static func random() -> CGFloat is useless outside of static func random() -> UIColor so you can declare the first method inside the second one