iOS中的随机颜色

时间:2014-09-23 15:43:01

标签: ios objective-c colors

我希望每次加载Navbar时都会使用不同的颜色。我在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;

问题是颜色范围太宽。

我希望它只选择您在此照片中看到的颜色:

enter image description here

是否可以使用此代码? +如果不是,我将如何创建一个从我定义的几个中选择随机颜色的相似颜色。

谢谢你的帮助。

3 个答案:

答案 0 :(得分:4)

这是使用您的确切颜色的复制/粘贴解决方案。

// 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];
}

注意:您应该使用arc4random_uniform()代替arc4random()来避免模偏差(尽管在这种情况下不是那么重要)。

答案 1 :(得分:1)

UIColor

以下是此代码:

-(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;
}

答案 2 :(得分:0)

这就是诀窍:

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];

谢谢@Rmaddy