从源自十六进制颜色的 UIColors 获取 RGB 值 [英] Getting RGB values from UIColors derived from Hex colors
问题描述
尝试从 UIColor 检索 RGB 值.但是, -[UIColor getRed:blue:green:alpha]
在我的情况下不起作用.该方法从不返回 YES,我认为这意味着颜色无法转换为 RGB.我认为这是因为我的 UIColor 是从十六进制颜色生成的(例如:#CCCCCC).
Trying to retrieve RGB values from a UIColor. However, -[UIColor getRed:blue:green:alpha]
is not working in my case. The method never returns YES which I think means that the color is not convertible into RGB. I assume this is because my UIColor was generated from a Hex color (ex: #CCCCCC).
你到底是如何从 iOS 中基于十六进制的 UIColors 获得 RGB 值的?
How the heck do you get RGB values from hex-based UIColors in iOS?
推荐答案
问题在于您给出的示例.颜色 #CCCCCC
是一种灰度颜色,这意味着 UIColor
不是用 RGB 创建的,而是用灰色创建的.换句话说,它是用 UIColor colorWithWhite:alpha:
创建的.由于您的 UIColor
是使用与 RGB 不同的颜色模型创建的,因此使用 getRed:green:blue:alpha:
返回 NO.
The problem is with the example you give. The color #CCCCCC
is a greyscale color meaning the UIColor
is not created with RGB but with a grey. In other words, it is created with UIColor colorWithWhite:alpha:
. Since your UIColor
is created with a different color model than RGB, using getRed:green:blue:alpha:
returns NO.
你能做的是:-
UIColor *color = // your color
CGFloat red, green, blue, alpha;
if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
CGFloat white;
if ([color getWhite:&white alpha:&alpha]) {
red = green = blue = white;
} else {
NSLog(@"Uh oh, not RGB or greyscale");
}
}
更新:
似乎从 iOS 8 开始,行为发生了一些变化.使用 UIColor colorWithWhite:alpha:
创建的颜色的 RGB 值可以通过 UIColor getRed:green:blue 获得:阿尔法:
.在早期版本的 iOS 中,这不起作用.因此需要我最初发布的代码.
It seems that the behavior changed a bit as of iOS 8. The RGB values of a color created with UIColor colorWithWhite:alpha:
can be obtained with UIColor getRed:green:blue:alpha:
. In earlier versions of iOS, this didn't work. Hence the need for the code I originally posted.
这篇关于从源自十六进制颜色的 UIColors 获取 RGB 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!