我使用以下函数来“改变”UIColor的饱和度,亮度和alpha: //UIColor *color = [self color:[UIColor redColor] saturation:0.5 brightness:0.5 alpha:0.5];- (UIColor *)color:(UIColor *)color saturation:(CGFloat)saturation brightne
//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)]; }
在iOS 11(GM)之前,这个工作非常好.但是,现在[UIColor getHue:saturation:brightness:alpha:]返回NO并且hsba值没有改变.
UIColor.h中的评论说:
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.
“兼容色彩空间”在这里意味着什么?我必须转换色彩空间吗?我该如何做到这一点?
我的.xcassets中的所有颜色都是sRGB.
编辑:一种修复方法是使用以下方式获取HSBA值:
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];如果颜色的颜色空间是sRGB,那么看起来UIColor getHue:saturation:brightness:方法不起作用,但如果颜色的颜色空间是扩展sRGB,它确实有效.
因此,解决方案是为颜色集资产中的每种颜色更新选定的颜色空间.
这可以在Swift Playground中演示如下.这将使用sRGB颜色空间创建颜色.
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)") } } }
这给出了输出:
kCGColorSpaceModelRGB 0.5 0.7 0.3 1
Failed with color space (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1)
更新上面的代码以使用CGColorSpace.extendedSRGB颜色空间可得到以下结果:
UIExtendedSRGBColorSpace 0.5 0.7 0.3 1 0.25 0.571428571428571 0.7