iOS中的随机颜色 [英] Random color in iOS

查看:296
本文介绍了iOS中的随机颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每次加载Navbar时都使用不同的颜色。我在viewDidApear中放置了以下代码:

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;

问题是颜色范围太宽。

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

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.

感谢您的帮助。

推荐答案

以下是使用您确切的颜色进行复制/粘贴的解决方案。

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

注意:您应使用 arc4random_uniform()而不是 arc4random()以避免模偏差(尽管在这种情况下不是很重要)。

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

这篇关于iOS中的随机颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆