Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 978
Stephen Avatar asked Jul 18 '16 11:07

Stephen


People also ask

How do you make a color darker and lighter?

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.

How do you make a color darker in Swift?

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 .

How do you make color more darker?

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.


1 Answers

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

like image 75
Stephen Avatar answered Sep 27 '22 23:09

Stephen