Skip to content

Instantly share code, notes, and snippets.

@adam-zethraeus
Last active March 7, 2023 09:28
Show Gist options
  • Save adam-zethraeus/041039741c6577c8b607f93a5660146f to your computer and use it in GitHub Desktop.
Save adam-zethraeus/041039741c6577c8b607f93a5660146f to your computer and use it in GitHub Desktop.
UIColor extension to generate a random pastel
import UIKit
public extension UIColor {
private static var randomLightness: CGFloat {
Double.random(in: 0...1)
}
private static var randomRGB: UIColor {
UIColor(
red: randomLightness,
green: randomLightness,
blue: randomLightness,
alpha: 1
)
}
/// Generate a random Pastel color.
///
/// Wikipedia:
///
/// *'Pastels belong to a pale family of colors, which, when described in the HSV color space, have high value and low saturation.'*
static var randomPastel: UIColor {
// 'HSB' and 'HSV' are different names for the same color spaces defined by:
// * Hue: the tint of the color.
// * Saturation: the distance of the color from a pure grey of the same Brightness.
// * Brightness/Value: How 'lit up' the color is. 0 = Black. 1 = 'Fully visible'.
// We define 'Pastel' as:
// * Any hue...
// * ...of low saturation [0.05, 0.4]...
// * ...and moderate to high brightness [0.6, 1.0].
// Generating a random number from zero to one in the HSB color space would not
// appear 'random' to humans. It would appear to show more of certain colors as
// they are 'stretched' in the space.
// See: https://en.wikipedia.org/wiki/HSL_and_HSV
// The RGB color space is also not uniform across human perception. We would
// prefer a random base color in the CGColorSpace.genericLab color space which
// is modelled to be uniform across human perception.
// However the L*a*b* color space has invalid regions when sampled naively — so
// randomization is harder.
// We stick to RGB.
let rgb = randomRGB
// Extract the sample's HSB/HSV values.
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
rgb.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
let pastelHue = hue
let pastelSaturation = 0.05 + (saturation * 0.35)
let pastelBrightness = 0.6 + (brightness * 0.4)
return UIColor(
hue: pastelHue,
saturation: pastelSaturation,
brightness: pastelBrightness,
alpha: 1
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment