简体   繁体   中英

Random color in iOS

I want to make my Navbar a different color each time its loaded. I have placed the following code in my viewDidApear:

CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

self.navigationBar.barTintColor = color;

the problem is that the color range is too wide.

I would like it to only select the colors that you see in this photo:

在此输入图像描述

Is it possible using this code? + if not how would i create a similar one that chooses a random color from a few that I have defined.

Thanks you for you help.

Here's a copy / paste solution using your exact colors.

// Declare somewhere in your code
typedef struct _Color {
    CGFloat red, green, blue;
} Color;

static Color _colors[12] = {
    {237, 230, 4},  // Yellow just to the left of center
    {158, 209, 16}, // Next color clockwise (green)
    {80, 181, 23},
    {23, 144, 103},
    {71, 110, 175},
    {159, 73, 172},
    {204, 66, 162},
    {255, 59, 167},
    {255, 88, 0},
    {255, 129, 0},
    {254, 172, 0},
    {255, 204, 0}
};

- (UIColor *)randomColor {
    Color randomColor = _colors[arc4random_uniform(12)];
    return [UIColor colorWithRed:(randomColor.red / 255.0f) green:(randomColor.green / 255.0f) blue:(randomColor.blue / 255.0f) alpha:1.0f];
}

NOTE : You should use arc4random_uniform() instead of arc4random() to avoid modulo bias (although not all that important in this case).

UIColor

Here's the code for this :

-(UIColor *)randomColor
{
   CGFloat hue = ( arc4random() % 256 / 256.0 );
   CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;
   CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;
   UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
   return color;
}

This did the trick:

NSArray *hues = @[ @76, @98, @160, @217, @292, @318, @327, @21, @30, @41, @48, @58 ];
NSNumber *hue = hues[arc4random_uniform(hues.count)];
UIColor *color = [UIColor colorWithHue:[hue doubleValue] / 360.0 saturation:1.0 brightness:1.0 alpha:1.0];

Thank you @Rmaddy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM