如何正确获取CGColor的颜色组件 [英] How to get color components of a CGColor correctly

查看:198
本文介绍了如何正确获取CGColor的颜色组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个黑色的UILabel;

I have a UILabel with black color;

我正在编写以下代码来获取黑色的组件。

i am writing the following code to get black color's components.

UIColor *aColor = [aLabel.textColor retain];
const CGFloat* components = CGColorGetComponents(aColor.CGColor);
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();

但总是给出绿色组​​件而不是黑色组件;

but always this is giving Green color components instead of black color components;

有人对此有所了解吗?

我是否通过了不同的颜色空间?

Am i passing different color space?

:-(请帮帮我。

推荐答案

最有可能出现错误的色彩空间。我想灰度色空间的alpha分量得到了您认为绿色组件应该在哪里。

我使用此函数从UIColor创建一个字符串,我只遇到RGB和灰度色彩空间,所以我只是将每种颜色解释为少于4(R + G + B + A)组件为灰度。

Most likely wrong colorspace. I guess the alpha component of the grayscale colorspace gets where you think the green component should be.
I use this function to create a string from UIColor, I only encounter RGB and Grayscale colorspaces, so I just interpret every color with less than 4 (R+G+B+A) components as grayscale.

if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
}
if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
    NSLog(@"no rgb colorspace");
    // do seomthing
}
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];

当然这种方法并不适用于所有情况,您应该根据您的要求采用它。

of course this method is not save for all cases, you should adopt it to your requirements.

这篇关于如何正确获取CGColor的颜色组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆