Search code examples
iosswiftuicolor

How to make UIColor "softer"


Often look at other applications that can make the color different but close to the color. It's like the two colors of the appendix.

How can UIColor be achieved?

enter image description here

enter image description here


Solution

  • A better solution than lowering the alpha (which may cause other things behind it to appear) is to lower the color's saturation.

    Here's a UIColor extension that gets the HSB of a color, lowers the saturation, and returns the new color with the same alpha:

    extension UIColor {
        func softer() -> UIColor {
            var h: CGFloat = 0
            var s: CGFloat = 0
            var b: CGFloat = 0
            var a: CGFloat = 0
            if self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
                // Change the 0.5 to suit your needs
                return UIColor(hue: h, saturation: s * 0.5, brightness: b, alpha: a)
            } else {
                return self
            }
        }
    }
    
    // Examples:    
    let orange = UIColor.orange
    let softOrange = orange.softer()
    let brown = UIColor(red: 0.4392, green: 0.2510, blue: 0.1882, alpha: 1.0)
    let softBrown = brown.softer()