是否有一種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