开发者

Converting from RGB to HSL with Objective C

I'm quite new to objective c but have been programming for a while. I started creating a function that would convert from RGB to HSL and back aga开发者_运维问答in but I get a feeling it is way too long and headed in the wrong direction. Does anyone know of a simple way to perform this conversion?


NSColor is missing in iPhone SDK. You can use this utility to convert from RGB to HSL space and back:

https://github.com/alessani/ColorConverter


You can use NSColor, I think.

CGFloat r, g, b, a, h, s, b, a2;
NSColor *c = [NSColor colorWithCalibratedRed:r green:g blue:b alpha:a];
[c getHue:&h saturation:&s brightness:&b alpha:&a2];

On second thought, I don't know if NSColor is available in the iPhone frameworks or not - isn't there a UIColor? Anyway I'll leave this answer in case someone searching for an OS X solution ends up here.


Here's what I'm using:

 static void RVNColorRGBtoHSL(CGFloat red, CGFloat green, CGFloat blue, CGFloat *hue, CGFloat *saturation, CGFloat *lightness)
{
    CGFloat r = red / 255.0f;
    CGFloat g = green / 255.0f;
    CGFloat b = blue / 255.0f;

    CGFloat max = MAX(r, g);
    max = MAX(max, b);
    CGFloat min = MIN(r, g);
    min = MIN(min, b);

    CGFloat h;
    CGFloat s;
    CGFloat l = (max + min) / 2.0f;

    if (max == min) {
        h = 0.0f;
        s = 0.0f;
    }

    else {
        CGFloat d = max - min;
        s = l > 0.5f ? d / (2.0f - max - min) : d / (max + min);

        if (max == r) {
            h = (g - b) / d + (g < b ? 6.0f : 0.0f);
        }

        else if (max == g) {
            h = (b - r) / d + 2.0f;
        }

        else if (max == b) {
            h = (r - g) / d + 4.0f;
        }

        h /= 6.0f;
    }

    if (hue) {
        *hue = roundf(h * 255.0f);
    }

    if (saturation) {
        *saturation = roundf(s * 255.0f);
    }

    if (lightness) {
        *lightness = roundf(l * 255.0f);
    }
}

And here's how to call it:

CGFloat h, s, l;
RVNColorRGBtoHSL(r, g, b,
                 &h, &s, &l);


You can add the UIColor-HSVAdditions.h/.m category to your app to add a set of operations to UIColor for working with hue, saturation and value. See http://bravobug.com/news/?p=448 and this ArsTechnica article also.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜