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 get a color, lets say:
[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
and get a UIColor which is a few shades darker and a few shades lighter. Does anyone know how to do this? Thank you.
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 (theL
in LAB is theluminance
value we are looking for).Using HandyUIKit (install it via Carthage) adds support for HCL and makes your life a lot easier:
There is also an option to apply a relative change (recommended):
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!
UIColor extension and fixing lighterColorForColor
Here is a UIColor category that also allows control over the amount of color change.
None of the solutions posted quite worked for all colours and shades, but then I stumbled across this library which provides a set of very well implemented extensions to UIColor.
Specifically it has a lighten function as part of its HSL implementation:
(UIColor *)lighten:(CGFloat)amount
- which works perfectly.user529758's solution in Swift:
Darker color:
Lighter color:
Use it like this:
EDIT: as @Anchu Chimala pointed out, for maximum flexibility, these methods should be implemented as an UIColor category. Also, from @Riley's idea, it may be a better idea to make the color proprtionally darker or lighter instead of adding or subtracting constant values. As @jrturton pointed out, it's not necessary to manipulate the RGB components; it's better to modify the brightness property itself. All in all: