Get lighter and darker color variations for a given UIColor

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

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

11条回答
  •  星月不相逢
    2021-01-30 02:52

    I want to provide another version using brightness & saturation instead of RGB

    extension UIColor {
      /**
       Create a ligher color
       */
      func lighter(by percentage: CGFloat = 30.0) -> UIColor {
        return self.adjustBrightness(by: abs(percentage))
      }
    
      /**
       Create a darker color
       */
      func darker(by percentage: CGFloat = 30.0) -> UIColor {
        return self.adjustBrightness(by: -abs(percentage))
      }
    
      /**
       Try to increase brightness or decrease saturation
       */
      func adjustBrightness(by percentage: CGFloat = 30.0) -> UIColor {
        var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        if self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
          if b < 1.0 {
            let newB: CGFloat = max(min(b + (percentage/100.0)*b, 1.0), 0.0)
            return UIColor(hue: h, saturation: s, brightness: newB, alpha: a)
          } else {
            let newS: CGFloat = min(max(s - (percentage/100.0)*s, 0.0), 1.0)
            return UIColor(hue: h, saturation: newS, brightness: b, alpha: a)
          }
        }
        return self
      }
    }
    

提交回复
热议问题