是否有一种Cocoa Touch方式将颜色从一种颜色空间转换为另一种颜色空间?如何将颜色从一个颜色空间转换为另一个颜色空间?
这段代码的末尾:
UIColor *grey = [UIColor colorWithWhite: 0.5 alpha: 1.0];
CGColorRef greyRef = [grey CGColor];
int x = CGColorGetNumberOfComponents(greyRef);
... x
是2
我之所以需要这个是我想要的颜色复制为CGGradientCreateWithColorComponents
颜色成分的列表,它需要一个色彩空间中的所有颜色。问题是灰色是在灰度色彩空间中,而不是RGB色彩空间。 (名字我想不起来了的那一刻,但它并不重要。)
CGGradientRef createGradient(NSInteger inCount, NSArray* inColors, CGFloat* inLocations) {
CGColorSpaceRef theColorspace = CGColorSpaceCreateDeviceRGB();
size_t numberOfComponents = 4;
NSInteger colorSize = numberOfComponents * sizeof(CGFloat);
CGFloat *theComponents = malloc(inCount * colorSize);
CGFloat *temp = theComponents;
for (NSInteger i = 0; i < inCount; i++) {
UIColor *theColor = [inColors objectAtIndex: i];
CGColorRef cgColor = [theColor CGColor];
const CGFloat *components = CGColorGetComponents(cgColor);
memmove(temp, components, colorSize);
temp += numberOfComponents;
}
CGGradientRef gradient = CGGradientCreateWithColorComponents(theColorspace,
theComponents, inLocations, inCount);
CGColorSpaceRelease(theColorspace);
free(theComponents);
return gradient;
}
我知道我可以找颜色灰度色彩空间,并将其转换。但那只能解决一个案例。从看at this question,我认为HSB也是如此。但是我想在这里写一些代码,而不再考虑它,这意味着不仅支持现在存在的色彩空间,而且支持Apple未来可能会增加的任何色彩空间。我运气不好吗?
哇,真的吗?这似乎是一个可怕的想法。 – damian 2013-06-07 10:34:55
@ damian毫无疑问这是丑陋的,但据我所知,它是唯一能可靠工作的方式,无论原始颜色是如何创建的。鉴于最初的问题是担心“不仅支持现在存在的色彩空间,而且苹果未来可能会增加色彩空间”我并不认为有一个好的选择。 – 2013-06-07 23:51:11
ThinkDifferent(tm) – damian 2013-06-08 06:34:50