Get lighter and darker color variations for a given UIColor

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

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

11条回答
  •  再見小時候
    2021-01-30 02:59

    Version with RGB values modification

    Here I put simple UIColor extension which is based on previous answers. It's working perfectly for me.

    Below demo:

    Colors manipulation code

    public extension UIColor {
    
        /**
         Create a lighter color
         */
        public func lighter(by percentage: CGFloat = 30.0) -> UIColor {
            return self.adjustBrightness(by: abs(percentage))
        }
    
        /**
         Create a darker color
         */
        public func darker(by percentage: CGFloat = 30.0) -> UIColor {
            return self.adjustBrightness(by: -abs(percentage))
        }
    
        /**
         Changing R, G, B values
         */
    
        func adjustBrightness(by percentage: CGFloat = 30.0) -> UIColor {
    
            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 pFactor = (100.0 + percentage) / 100.0
    
                let newRed = (red*pFactor).clamped(to: 0.0 ... 1.0)
                let newGreen = (green*pFactor).clamped(to: 0.0 ... 1.0)
                let newBlue = (blue*pFactor).clamped(to: 0.0 ... 1.0)
    
                return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: alpha)
            }
    
            return self
        }
    }
    

    Clamped function Extension to easily keep values between min and max.

    extension Comparable {
    
        func clamped(to range: ClosedRange) -> Self {
    
            if self > range.upperBound {
                return range.upperBound
            } else if self < range.lowerBound {
                return range.lowerBound
            } else {
                return self
            }
        }
    }
    

提交回复
热议问题