Get lighter and darker color variations for a given UIColor

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

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

11条回答
  •  独厮守ぢ
    2021-01-30 02:42

    Kenji-Tran's answer works fine, as long as your starting color is not black (brightness value 0). With the addition of a few lines of extra code, you can also make black "lighter" (i.e. brighten it to a grayscale or color value).

    Note: I wasn't able to add this change using an Edit and I'm not allowed to comment on Kenji-Tran's answer due to my "new boy" rep, therefore I found no other way to share my knowledge on SO then by posting a new answer. I hope that's okay.

    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 {
            /**
             Below is the new part, which makes the code work with black as well as colors
            */
            let newB: CGFloat
            if b == 0.0 {
                newB = max(min(b + percentage/100, 1.0), 0.0)
            } else {
                newB = 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
      }
    }
    

提交回复
热议问题