I am using the following function to "change" the saturation, brightness and alpha of a UIColor
:
//UIColor *color = [self color:[UIColor redColor] saturation:0.5 brightness:0.5 alpha:0.5];
- (UIColor *)color:(UIColor *)color saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha {
CGFloat h, s, b, a;
[color getHue:&h saturation:&s brightness:&b alpha:&a];
return [UIColor colorWithHue:h saturation:(s * saturation) brightness:(b * brightness) alpha:(a * alpha)];
}
Prior to iOS 11 (GM) this was working perfectly fine. However, now [UIColor getHue:saturation:brightness:alpha:]
returns NO
and the hsba values aren't getting changed.
Comment in UIColor.h
says:
If the receiver is of a compatible color space, any non-NULL parameters are populated and 'YES' is returned. Otherwise, the parameters are left unchanged and 'NO' is returned.
What does "compatible color space" mean here? Do I have to convert color spaces? How do I accomplish that? All the colors in my .xcassets are in sRGB.
EDIT: Kind of a fix is to use the following way to get the HSBA values:
CGFloat rTemp, gTemp, bTemp, aTemp;
[color getRed:&rTemp green:&gTemp blue:&bTemp alpha:&aTemp];
CGFloat h, s, b, a;
[[UIColor colorWithRed:rTemp green:gTemp blue:bTemp alpha:aTemp] getHue:&h saturation:&s brightness:&b alpha:&a];
It appears that the UIColor getHue:saturation:brightness:
method doesn't work if the color's color space is sRGB but it does work if the color's color space is Extended sRGB.
So the solution is to update the selected Color Space for each of your colors in your color set asset.
This can be demonstrated in a Swift Playground as follows. This creates a color using the sRGB color space.
if let cs = CGColorSpace(name: CGColorSpace.sRGB) {
if let cc = CGColor(colorSpace: cs, components: [0.5, 0.7, 0.3, 1.0]) {
let color = UIColor(cgColor: cc)
print(color)
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
if color.getHue(&h, saturation: &s, brightness: &b, alpha: nil) {
print(h, s, b)
} else {
print("Failed with color space \(cs)")
}
}
}
This gives the output:
kCGColorSpaceModelRGB 0.5 0.7 0.3 1
Failed with color space (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1)
Updating the above code to use the CGColorSpace.extendedSRGB
color space gives the following results:
UIExtendedSRGBColorSpace 0.5 0.7 0.3 1
0.25 0.571428571428571 0.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With