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 ...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With