获得objective-c中的颜色分量

Las*_*zlo 1 components objective-c uicolor

以下是获取RGB颜色分量的代码片段.如果_countComponents小于4,例如两个,我该怎么办?我试图获得颜色为灰色的组件[UIColor grayColor]

int _countComponents = CGColorGetNumberOfComponents(colorRef);

if (_countComponents == 4) {
    const CGFloat *_components = CGColorGetComponents(colorRef);
    CGFloat red     = _components[0];
    CGFloat green = _components[1];
    CGFloat blue   = _components[2];
    CGFloat alpha = _components[3];
Run Code Online (Sandbox Code Playgroud)

Cal*_*leb 5

如果您有一个UIColor实例并且您想要它的RGB值,为什么不使用该-getRed:green:blue:alpha:方法?

CGFloat r, g, b, a;
BOOL success = [myColor getRed:&r green:&g blue:&b alpha:&a];
if (success) {
    // the color was converted to RGB successfully, go ahead and use r,g,b, and a.
}
Run Code Online (Sandbox Code Playgroud)