Last active
September 18, 2024 20:50
-
-
Save asarode/7b343fa3fab5913690ef to your computer and use it in GitHub Desktop.
Generating random UIColor in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func generateRandomColor() -> UIColor { | |
let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0 | |
let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white | |
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black | |
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) | |
} |
Thank you!
Thanks! And if you prefer as a variable..
var randomColor: UIColor {
let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0
let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}
Here's another version, but with optional parameters:
import UIKit
extension UIColor {
static func random(hue: CGFloat = CGFloat.random(in: 0...1),
saturation: CGFloat = CGFloat.random(in: 0.5...1), // from 0.5 to 1.0 to stay away from white
brightness: CGFloat = CGFloat.random(in: 0.5...1), // from 0.5 to 1.0 to stay away from black
alpha: CGFloat = 1) -> UIColor {
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks