在Objective C中将HSB颜色转换为RGB

时间:2012-07-28 21:07:21

标签: objective-c ios colors

我正在尝试使用this algorithm将HSB值转换为RGB值,但我没有得到正确的值。我有一个29的固定s,100的固定b,并且为h值生成0-360之间的随机整数,并将它们送入函数以获得RGB:

enter image description here

float h = (arc4random() % 360);
float s = 29;
float b = 100;
HSL2RGB(h, s, b, &red, &green, &blue);
NSLog(@"r:%f g:%f b:%f", red, green, blue);

输出:

r:2971.000000 g:2971.000000 b:2971.000000

我也试过了:

float h = (arc4random() % 360)/1000.0;
float s = 0.29;
float b = 1.0;
HSL2RGB(h, s, b, &red, &green, &blue);
NSLog(@"r:%f g:%f b:%f", red, green, blue);

输出:

r:1.000000 g:1.000000 b:1.000000

我做错了什么,或者这个算法搞砸了?

2 个答案:

答案 0 :(得分:9)

您可以直接使用UIKit轻松获取使用HSB构建的颜色的RGB分量。

UIColor *color = [UIColor colorWithHue: hue saturation: saturation
                            brightness: brightness alpha: alpha];
if ( [color getRed: &red green: &green blue: &blue alpha: &alpha] ) {
    // color converted
}

如果你关心的只是使用颜色,你可以跳过if并使用它。

根据Apple的UIColor documentation

  

如果颜色位于兼容的颜色空间中,颜色将转换为RGB格式,其组件将返回到您的应用程序。如果颜色不在兼容的颜色空间中,则参数不变。

在这种情况下,兼容的色彩空间是RGB或HSB。

答案 1 :(得分:5)

我不知道你的算法,但我应该使用这个算法:

typedef struct
{
    double r;       // percent [0 - 1]
    double g;       // percent [0 - 1]
    double b;       // percent [0 - 1]
    double a;       // percent [0 - 1]
} RGBA;

typedef struct
{
    double h;       // angle in degrees [0 - 360]
    double s;       // percent [0 - 1]
    double v;       // percent [0 - 1]
} HSV;

- (RGBA)RGBfromHSV:(HSV)value
{
    double      hh, p, q, t, ff;
    long        i;
    RGBA        out;
    out.a       = 1;

    if (value.s <= 0.0) // < is bogus, just shuts up warnings
    {       
        if (isnan(value.h)) // value.h == NAN
        {   
            out.r = value.v;
            out.g = value.v;
            out.b = value.v;
            return out;
        }

        // error - should never happen
        out.r = 0.0;
        out.g = 0.0;
        out.b = 0.0;
        return out;
    }

    hh = value.h;
    if(hh >= 360.0) hh = 0.0;
    hh /= 60.0;
    i = (long)hh;
    ff = hh - i;
    p = value.v * (1.0 - value.s);
    q = value.v * (1.0 - (value.s * ff));
    t = value.v * (1.0 - (value.s * (1.0 - ff)));

    switch(i)
    {
        case 0:
            out.r = value.v;
            out.g = t;
            out.b = p;
            break;
        case 1:
            out.r = q;
            out.g = value.v;
            out.b = p;
            break;
        case 2:
            out.r = p;
            out.g = value.v;
            out.b = t;
            break;

        case 3:
            out.r = p;
            out.g = q;
            out.b = value.v;
            break;
        case 4:
            out.r = t;
            out.g = p;
            out.b = value.v;
            break;
        case 5:
        default:
            out.r = value.v;
            out.g = p;
            out.b = q;
            break;
    }
    return out;     
}

我将它用于我的项目中,我没有遇到任何问题。 :)