Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexwal/51cb721d299ae5fb204abfa8faef8e11 to your computer and use it in GitHub Desktop.
Save alexwal/51cb721d299ae5fb204abfa8faef8e11 to your computer and use it in GitHub Desktop.
Randomly generate pastel UIColor in Swift
// Adapted from Stack Overflow answer by David Crow http://stackoverflow.com/a/43235
// Question: Algorithm to randomly generate an aesthetically-pleasing color palette by Brian Gianforcaro
// Method randomly generates a pastel color, and optionally mixes it with another color
import UIKit
func randomPastelColor(mixedWith mixColor: UIColor? = nil) -> UIColor {
// Mix the color
let mixColor: UIColor = mixColor ?? .lightGray
var mixRed: CGFloat = 0, mixGreen: CGFloat = 0, mixBlue: CGFloat = 0;
mixColor.getRed(&mixRed, green: &mixGreen, blue: &mixBlue, alpha: nil)
// Randomly generate number in closure
let randomColor: () -> CGFloat = { CGFloat(arc4random() % 256 ) / 256 }
let red = (randomColor() + mixRed) / 2;
let green = (randomColor() + mixGreen) / 2;
let blue = (randomColor() + mixBlue) / 2;
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment