Search code examples
iosobjective-calgorithmios6colors

Convert RGB Value to UIColor?


Given a huge list of RGB values, I would like to associate and pair them to a standard UIColor. For example, (255,0,0) is the "common" Red color. I would like to pair and label values like (254,85,44) and (193,0,1) as "Red" as well. As long as they are close to a shade of red I would like to say it is "red". What would be the best way to accomplish this? I tried testing for luminance and even comparing it to the standard (255,0,0) for a generic formula but was unsuccessful. Any suggestions?


Solution

  • Your best bet is to convert the RBG value to HSL or HSV (sometimes referred to as HSB). Then check the hue value. If the hue comes out in the range 0-15 or 340-360 (adjust these ranges to suit your own definition of "red"), then you could consider the color to be red. Of course some of these will be nearly black or white to you may also want to limit the luminance or brightness values as well.

    int red = ... // your red value (0 - 255)
    int green = ... // your green value (0 - 255)
    int blue = ... // your blue value (0 - 255)
    UIColor *RGBColor = [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0  alpha:1.0];
    CGFloat hue, saturation, brightness;
    if ([RGBColor getHue:&hue saturation:&saturation brightness:&brightness alpha:nil]) {
        // Replace 15 and 240 with values you consider to be "red"
        if (hue < 15/360.0 || hue > 240/360.0) {
            // this can be considered "red"
        }
    } else {
        // oops - can't convert
    }