Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random color hex in Objective-C ?

How do I generate a random color hexadecimal in Objective-C ?

I need a color hexdecimal , I don't need a random color. It is complicated ...

like image 520
Kristina Brooks Avatar asked May 26 '10 16:05

Kristina Brooks


2 Answers

I think should work for you. Arc4random() is far better in the way of performance & ... accuracy than rand(). Rand() also needs to be seeded before use.

// 16777215 is FFFFFF
NSInteger *baseInt = arc4random() % 16777216;
NSString *hex = [NSString stringWithFormat:@"%06X", baseInt];

Edit: Edited based on comment regarding formatting.

like image 91
Matt S Avatar answered Nov 15 '22 09:11

Matt S


You can use the standard C library routine rand() in your Objective-C application. From there, then, you'll want to call it three times to get random values for each of the red, green, and blue channels of your random color. You'll want to mod (%) the value by the maximum value the channel can have- typically 256. From there you can construct your NSColor appropriately. So your code might look something like:

int red = rand() % 255;
int green = rand() % 255;
int blue = rand() % 255;
NSColor* myColor = [NSColor colorWithCalibratedRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];

Because NSColor takes floats instead of integers a better approach would be to divide the random values by RAND_MAX right from the start:

float rand_max = RAND_MAX;
float red = rand() / rand_max;
float green = rand() / rand_max;
float blue = rand() / rand_max;
NSColor* myColor = [NSColor colorWithCalibratedRed:red green:green blue:blue alpha:1.0];

This latter code will not limit the number of colors to a 24-bit spectrum.

like image 24
fbrereto Avatar answered Nov 15 '22 09:11

fbrereto