How can I modify a UIColor's hue, brightness and saturation?
You can call getHue:saturation:brightness:alpha:
on your color, then adjust the values, then create a new color with your adjusted components using +[UIColor colorWithHue:saturation:brightness:alpha:]
CGFloat hue, saturation, brightness, alpha ;
BOOL ok = [ <color> getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha ] ;
if ( !ok ) {
// handle error
}
// ... adjust components..
UIColor * newColor = [ UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha ] ;
Here is swift UIColor
extension you might find useful:
extension UIColor {
func modified(withAdditionalHue hue: CGFloat, additionalSaturation: CGFloat, additionalBrightness: CGFloat) -> UIColor {
var currentHue: CGFloat = 0.0
var currentSaturation: CGFloat = 0.0
var currentBrigthness: CGFloat = 0.0
var currentAlpha: CGFloat = 0.0
if self.getHue(¤tHue, saturation: ¤tSaturation, brightness: ¤tBrigthness, alpha: ¤tAlpha){
return UIColor(hue: currentHue + hue,
saturation: currentSaturation + additionalSaturation,
brightness: currentBrigthness + additionalBrightness,
alpha: currentAlpha)
} else {
return self
}
}
}
Unfortunately it's quite a hassle to change any of the hsba
or rgba
values of a UIColor by default. Using HandyUIKit (install it via Carthage) makes your life a lot easier:
import HandyUIKit
// each line creates a new UIColor object with the new value
color.change(.hue, to: 0.1)
color.change(.brightness, to: 0.2)
color.change(.saturation, to: 0.3)
color.change(.alpha, to: 0.4)
// chaining them returns a single new object with all values changed
color.change(.hue, to: 0.5)
.change(.brightness, to: 0.6)
.change(.saturation, to: 0.7)
There are also options to apply relative changes:
// create a new UIColor object with hue & brightness increased by 0.2
color.change(.hue, by: 0.2)
.change(.brightness, by: 0.2)
The library also adds some other handy UI features into your project – checkout its README on GitHub for more details.
I hope it helps!