UIColorの色を暗くする

Swift 4.2.1

現在の色から暗めの色に明度(brightness/lightness)を変更するための UIColor Extension。

extension UIColor {
    
    func dark(brightnessRatio: CGFloat = 0.8) -> UIColor {
        var hue: CGFloat = 0
        var saturation: CGFloat = 0
        var brightness: CGFloat = 0
        var alpha: CGFloat = 0
        
        if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
            return UIColor(hue: hue, saturation: saturation, brightness: brightness * brightnessRatio, alpha: alpha)
        } else {
            return self
        }
    }
}

使い方

view.backgroundColor = view.backgroundColor.dark()