Search code examples
cocoanscolor

Is there any method in Cocoa that helps iterating through all NSColor values(R,G,B only, alpha not touched)?


I need a function that for a given R,G,B values returns the next color.

By saying the next color I mean the color which one of the components change by 1(assuming that R,G,B values are of range 0-255).

It has to be constructed that way that starting from the white color(or black alternatively) you can iterate throught all of the colors(which count is 255*255*255). It would be nice, but not required that after iterating throught all of the colors, they are being repeated from the beginning.


Solution

  • You could base color retrieval on color lists, either using a custom or Apple one like "Web Safe Colors":

    NSColorList* cl = [NSColorList colorListNamed:@"Web Safe Colors"];
    NSLog(@"%@", cl);
    for (NSString *key in [cl allKeys]) { 
        NSLog(@" * %@ - %@", key, [cl colorWithKey:key]);
    }
    

    If you need more and the order doesn't matter, you could use e.g. +colorWithColorSpace:components:count::

    uint32_t c = 0;
    // increment c whenever a color is requested ...
    
    CGFloat components[4] = { 
        ((c & 0xFF0000) >> 16) / 256.0, 
        ((c & 0x00FF00) >> 8 ) / 256.0,
        ((c & 0x0000FF) >> 0 ) / 256.0,
        0.0 
    };
    NSColor *color = [NSColor colorWithColorSpace:[NSColorSpace genericRGBColorSpace] 
                                       components:components 
                                            count:4];