How to get different lighter and darker variations of a given UIColor in Swift?
Tints are lighter versions of the color that are made by mixing a color with white, whereas shades are darker versions of the color that are made by mixing a color with black.
The first step is to extract red, green, blue, and alpha components from the current UIColor . Then, to each color component, add a componentDelta to make the color lighter or darker. Each color component value is between 0 and 1 .
The answer would seem to be, add some black, then add another color if necessary to correct it. If it's too cool, add a smidgen red. One more comment: Adding a color's complement to it will not necessarily make it darker. It might not change the value much at all.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With