It just takes a little bit of math. The following code is just the important parts of the custom class I created for conversion. The "HSBColor" class stores just the hue, saturation, and brightness and I provide functions to get the components of it or a UIColor if I need to actually use it for something in the system.
Note: This code will not work as is unless you define an HSBColor class with hue, brightness, and saturation properties.
+(void)max:(int*)max andMin:(int*)min ofArray:(float[])array
{
*min=0;
*max=0;
for(int i=1; i<3; i++)
{
if(array[i] > array[*max])
*max=i;
if(array[i] < array[*min])
*min=i;
}
}
+(HSBColor*)colorWithRed:(float)red Green:(float)green Blue:(float)blue
{
HSBColor* toReturn = [[[HSBColor alloc] init] autorelease];
float colorArray[3];
colorArray[0] = red;
colorArray[1] = green;
colorArray[2] = blue;
//NSLog(@"RGB: %f %f %f",colorArray[0],colorArray[1],colorArray[2]);
int max;
int min;
[self max:&max andMin:&min ofArray:colorArray];
if(max==min)
{
toReturn.hue=0;
toReturn.saturation=0;
toReturn.brightness=colorArray[0];
}
else
{
toReturn.brightness=colorArray[max];
toReturn.saturation=(colorArray[max]-colorArray[min])/(colorArray[max]);
if(max==0) // Red
toReturn.hue = (colorArray[1]-colorArray[2])/(colorArray[max]-colorArray[min])*60/360;
else if(max==1) // Green
toReturn.hue = (2.0 + (colorArray[2]-colorArray[0])/(colorArray[max]-colorArray[min]))*60/360;
else // Blue
toReturn.hue = (4.0 + (colorArray[0]-colorArray[1])/(colorArray[max]-colorArray[min]))*60/360;
}
return toReturn;
}
+(HSBColor*)colorWithSystemColor:(UIColor*)color
{
const CGFloat* components = CGColorGetComponents(color.CGColor);
return [self colorWithRed:components[0] Green:components[1] Blue:components[2]];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…