Search code examples
iosswiftcolorscore-graphicsuicolor

Get lighter and darker color variations for a given UIColor


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

enter image description here


Solution

  • Updated

    Use below UIColor Extension:

    extension UIColor {
    
        func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
            return self.adjust(by: abs(percentage) )
        }
    
        func darker(by percentage: CGFloat = 30.0) -> UIColor? {
            return self.adjust(by: -1 * abs(percentage) )
        }
    
        func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
            var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
            if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
                return UIColor(red: min(red + percentage/100, 1.0),
                               green: min(green + percentage/100, 1.0),
                               blue: min(blue + percentage/100, 1.0),
                               alpha: alpha)
            } else {
                return nil
            }
        }
    }
    

    Usage:

    let color = UIColor(red:0.96, green:0.54, blue:0.10, alpha:1.0)
    color.lighter(30) // returns lighter color by 30%
    color.darker(30) // returns darker color by 30%
    

    instead of .lighter() and .darker(), you can use .adjust() with positive values for lightening and negative values for darkening

    color.adjust(-30) // 30% darker color
    color.adjust(30) // 30% lighter color
    

    Output:

    enter image description here