在iPhone上从RGB更改为HSB? [英] Change from RGB to HSB on iPhone?

查看:139
本文介绍了在iPhone上从RGB更改为HSB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜寻了年龄,找不到办法做到这一点。任何人有一个想法?有一个NSColor的方式来做它的mac,但没有为iPhone我可以看到。在我的应用程序的想法是,用户键入一个HEX代码(我已经设法进入RGB),它已更改为HSB。

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?

推荐答案

它只是需要一点点数学。以下代码只是我为转换创建的自定义类的重要部分。 HSBColor类只存储色相,饱和度和亮度,我提供函数来获取它的组件或UIColor,如果我需要实际使用它在系统中的东西。

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.

注意:除非您定义带有色调,亮度和饱和度属性的HSBColor类别,否则此代码将无法正常工作。

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

这篇关于在iPhone上从RGB更改为HSB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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