开发者

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 complicate开发者_运维知识库d ...


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.


There is an article on cocoadev (including code examples) on writing a screensaver - with random colors:

  • http://cocoadevcentral.com/articles/000088.php


Just for a short note:

Depending on your needs, it's possible that you should consider to write a not-so-random color generator. (For example when want to set up "rules" for the visibility of the generated colors.) So it's possible that you need to get the color code by limiting the random-generated values in HSB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜