Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - Change from RGB to HSB on iPhone?

I've googled for ages and can't find a way to do this. Anybody got an idea? There is an NSColor way of doing it for mac, but nothing for iPhone that I can see. The idea in my app is that the user types in a HEX code (which i have managed to get into RGB) and it's changed into HSB.

Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...