Reputation: 45
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.
Upvotes: 4
Views: 2495
Reputation: 1034
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;
}
Upvotes: 1
Reputation: 45
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
Upvotes: 0
Reputation: 5566
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).
Upvotes: 4