<> Posted on June 7, 2015 in Code
One of the open source libraries that WheelMasks uses more intensely is the HUSL color space, by Alexei Boronine. HUSL is an extension of CIELUV that enables its chroma component to be expressed as a percentage regardless of the lightness so it can be used in a similar way as HSL.
The official repository of husl had a C port that I could easily include into my XCode project but it wasn't up to date with the latest implementation of the official library written in CoffeeScript. Instead of working on the C code, I opted to write an Objective-C port that takes advantage of ARC and Objective-C's collection classes. I first tried writting a Swift version, but I abandoned it since it was too slow. That was before Swift 1.2 had been released, so I should probably take a look at it again to see if performance has improved.
Since I wanted to contribute back to HUSL in some way I've spent some time making sure my port passes the official test suite and I've released it on GitHub under the name of husl-objc. I've also released it as a Pod for CocoaPods. If you think you can use it in your projects just download the library from GitHub or simply add pod 'husl-objc'
to your Podfile.
Once you've added it to your project, you just need to import the header husl_objc.h
and you'll be able to use these functions to convert between RGB and HUSL (and its variant, HUSLp):
// Hue is a value between 0 and 360, saturation and lightness between 0 and 100.
// Stores the RGB in values between 0 and 1.
void huslToRgb(CGFloat hue, CGFloat saturation, CGFloat lightness, CGFloat *red,
CGFloat *green, CGFloat *blue);
// Red, green and blue values between 0 and 1, stores the husl components with
// hue between 0 and 360, saturation and lightness between 0 and 100.
void rgbToHusl(CGFloat red, CGFloat green, CGFloat blue, CGFloat *hue,
CGFloat *saturation, CGFloat *lightness);
// Hue is a value between 0 and 360, saturation and lightness between 0 and 100.
// Stores the RGB in values between 0 and 1.
void huslpToRgb(CGFloat hue, CGFloat saturation, CGFloat lightness, CGFloat *red,
CGFloat *green, CGFloat *blue);
// Red, green and blue values between 0 and 1, stores the huslp components with
// hue between 0 and 360, saturation and lightness between 0 and 100.
void rgbToHuslp(CGFloat red, CGFloat green, CGFloat blue, CGFloat *hue,
CGFloat *saturation, CGFloat *lightness);