Get lighter and darker color variations for a given UIColor

前端 未结 11 2195
一生所求
一生所求 2021-01-30 02:32

How to get different lighter and darker variations of a given UIColor in Swift?

11条回答
  •  滥情空心
    2021-01-30 02:44

    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
    

    On a large project .................

    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)
    

提交回复
热议问题