ios – 是否有将UIColor转换为色相饱和度亮度的功能?

前端之家收集整理的这篇文章主要介绍了ios – 是否有将UIColor转换为色相饱和度亮度的功能?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以用RGB值设置uicolor:
[UIColor colorWithRed:0.53 green:0.37 blue:0.11 alpha:1.00];

我可以设置uicolor与hsb值:

[UIColor colorWithHue:0.10 saturation:0.16 brightness:0.13 alpha:1.00];

我也可以将其转换回RGB:

CGFloat* colors = CGColorGetComponents(Color1.CGColor);

但是我可以如何从uicolor获得HSB?

解决方法

使用UIColor方法
getHue:饱和度:亮度:阿尔法:

从苹果文档:
“返回构成HSB颜色空间中颜色的组件.”

- (BOOL)getHue:(CGFloat *)hue saturation:(CGFloat *)saturation brightness:(CGFloat *)brightness alpha:(CGFloat *)alpha

例:

UIColor *testColor = [UIColor colorWithRed:0.53 green:0.37 blue:0.11 alpha:1.00];

CGFloat hue;
CGFloat saturation;
CGFloat brightness;
CGFloat alpha;
BOOL success = [testColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
NSLog(@"success: %i hue: %0.2f,saturation: %0.2f,brightness: %0.2f,alpha: %0.2f",success,hue,saturation,brightness,alpha);

NSLog输出

success: 1 hue: 0.10,saturation: 0.79,brightness: 0.53,alpha: 1.00

以下是@WhiteTiger提供的方法的更正版本:

// Test values
CGFloat red = 0.53;
CGFloat green = 0.37;
CGFloat blue = 0.11;

CGFloat hue = 0;
CGFloat saturation = 0;
CGFloat brightness = 0;

CGFloat minRGB = MIN(red,MIN(green,blue));
CGFloat maxRGB = MAX(red,MAX(green,blue));

if (minRGB==maxRGB) {
    hue = 0;
    saturation = 0;
    brightness = minRGB;
} else {
    CGFloat d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
    CGFloat h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
    hue = (h - d/(maxRGB - minRGB)) / 6.0;
    saturation = (maxRGB - minRGB)/maxRGB;
    brightness = maxRGB;
}
NSLog(@"hue: %0.2f,value: %0.2f",brightness);

NSLog输出

hue: 0.10,value: 0.53

原文链接:https://www.f2er.com/iOS/336902.html

猜你在找的iOS相关文章