How to get different lighter and darker variations of a given UIColor in Swift?
To save anyone typing, the simple practical version is just
extension UIColor {
var darker: UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
guard self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) else {
print("** some problem demuxing the color")
return .gray
}
let nudged = b * 0.5
return UIColor(hue: h, saturation: s, brightness: nudged, alpha: a)
}
}
use like
something.color = .yellow.darker
or
backgroundColor = backgroundColor.darker
You should definitely extend Apple's pattern:
.withAlphaComponent(_ alpha: CGFloat)
So, have:
.withBrightnessComponent(_ alpha: CGFloat)
and distinctly
.withBrightnessComponentAdjustedBy(percentage: CGFloat)
and/or
.withBrightnessComponentMultipliedBy(factor: CGFloat)