Get lighter and darker color variations for a given UIColor

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

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

11条回答
  •  醉梦人生
    2021-01-30 02:48

    Using lukszar clampled function, I wrote this function for the UIColor extension, using real proportions of RGB values. I hope it is helpful

    public extension UIColor {
    
      public func lighter(by percentage: CGFloat = 30.0) -> UIColor {
        return self.adjustBrightness(by: abs(percentage))
      }
    
      public func darker(by percentage: CGFloat = 30.0) -> UIColor {
        return self.adjustBrightness(by: -abs(percentage))
      }
    
      func adjustBrightness(by percentage: CGFloat = 30.0) -> UIColor {
    
        let ratio = percentage/100
    
        var red:   CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue:  CGFloat = 0.0
        var alpha: CGFloat = 0.0
    
        if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
          let newRed =   (red   + ((ratio < 0) ? red   * ratio : (1 - red)   * ratio)).clamped(to: 0.0 ... 1.0)
          let newGreen = (green + ((ratio < 0) ? green * ratio : (1 - green) * ratio)).clamped(to: 0.0 ... 1.0)
          let newBlue =  (blue  + ((ratio < 0) ? blue  * ratio : (1 - blue)  * ratio)).clamped(to: 0.0 ... 1.0)
          return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: alpha)
        }
        return self
      }
    }
    

提交回复
热议问题