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

StackOverflow https://stackoverflow.com/questions/2940002

  •  05-10-2019
  •  | 
  •  

Question

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.

Was it helpful?

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];

OTHER TIPS

It is not clear what you mean with "next color" but you can easily have a counter from which you extract the components:

uint32 color = 0;

uint8 r = color%256;
uint8 g = (color/256) % 256;
uint8 b = (color/(256*256)) % 256;

// use color

++color;

otherwise you can just generate random colors and keep track of already used ones with an NSSet. Of course you are gonna pack 3 components in a single object, like an int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top