生成随机 UIColor [英] Generate a random UIColor

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

问题描述

我尝试为 UILabel 获取随机颜色...

I try to get a random color for UILabel...

- (UIColor *)randomColor
{
    int red = arc4random() % 255 / 255.0;
    int green = arc4random() % 255 / 255.0;
    int blue = arc4random() % 255 / 255.0;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    NSLog(@"%@", color);
    return color;
}

并使用它:

[mat addAttributes:@{NSForegroundColorAttributeName : [self randomColor]} range:range];

但颜色总是黑色.怎么了?

But color is always black. What is wrong?

推荐答案

因为您已将颜色值分配给 int 变量.使用 float(或 CGFloat)代替.另外(如@stackunderflow 所说),其余部分必须取模 256 以覆盖整个范围 0.0 ... 1.0:

Because you have assigned the colour values to int variables. Use float (or CGFloat) instead. Also (as @stackunderflow's said), the remainder must be taken modulo 256 in order to cover the whole range 0.0 ... 1.0:

CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;

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

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