views:

412

answers:

2

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 again 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?

+2  A: 

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.

Carl Norum
+1, though HSL isn't quite the same as HSB/HSV. The H and S should be the same, though.
Wevah
@Wevah, wikipedia says it's not very standardized, and that any of the names can go with any of the models. I'm not enough of an expert to know the subtleties though.
Carl Norum
Well, they're *sort* of standard. Almost. Mostly it's just unfortunate that the built-in stuff doesn't handle HSL(ightness). :/ And if he really does want HSV/HSB, then your answer is perfect!
Wevah
There is indeed a UIColor! (I missed the `iphone` tag, too.)
Wevah
Thanks Carl, I tried using UIColor which got me a little closer but I get the error 'UIColor may not respond to -getHue:saturation:brightness:alpha'
treeba
+1  A: 

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.

progrmr