Get Slightly Lighter and Darker Color from UIColor

前端 未结 19 2692
猫巷女王i
猫巷女王i 2020-12-07 07:08

I was looking to be able to turn any UIColor into a gradient. The way I am intending to do this is by using Core Graphics to draw a gradient. What I am trying to do is to ge

19条回答
  •  悲&欢浪女
    2020-12-07 07:44

    All other answers in this thread use either the RGB color system or simply change the hue or brightness value of the HSB system. As explained in detail in this great blog post the correct way of making a color lighter or darker is to change its luminance value. None of the other answers does that. If you want to do it right, then use my solution or write your own after reading the blog post.


    Unfortunately it's quite a hassle to change any of the attributes of a UIColor by default. Also Apple doesn't even support any LAB-based color space like HCL in the UIColor class (the L in LAB is the luminance value we are looking for).

    Using HandyUIKit (install it via Carthage) adds support for HCL and makes your life a lot easier:

    import HandyUIKit    
    
    let color = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
    
    // create a new UIColor object with a specific luminance (slightly lighter)
    color.change(.luminance, to: 0.7)
    

    There is also an option to apply a relative change (recommended):

    // create a new UIColor object with slightly darker color
    color.change(.luminance, by: -0.2)
    

    Note that HandyUIKit also adds some other handy UI features into your project – checkout its README on GitHub for more details.

    I hope it helps!

    Disclaimer: I'm the author of HandyUIKit.

提交回复
热议问题