生成随机UIColor

Tat*_*yak 19 objective-c uicolor

我尝试为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;
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

[mat addAttributes:@{NSForegroundColorAttributeName : [self randomColor]} range:range];
Run Code Online (Sandbox Code Playgroud)

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

PS抱歉我的英文)

kko*_*dev 36

[UIColor colorWithHue:drand48() saturation:1.0 brightness:1.0 alpha:1.0];
Run Code Online (Sandbox Code Playgroud)

或者在Swift中:

UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)
Run Code Online (Sandbox Code Playgroud)

随意随意或根据自己的喜好调整饱和度和亮度.


Mar*_*n R 24

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

CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;
Run Code Online (Sandbox Code Playgroud)


Jas*_*min 8

试试这个

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];
Run Code Online (Sandbox Code Playgroud)


upp*_*t99 8

使用类 var 的Swift解决方案random

extension UIColor {
    class var random: UIColor {
        return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用就像任何其他的内置UIColor类变量(.red.blue.white等),例如:

view.backgroundColor = .random
Run Code Online (Sandbox Code Playgroud)


Jbr*_*son 6

这是一个快速版本,制作成UIColor扩展:

extension UIColor {
    class func randomColor(randomAlpha: Bool = false) -> UIColor {
        let redValue = CGFloat(arc4random_uniform(255)) / 255.0;
        let greenValue = CGFloat(arc4random_uniform(255)) / 255.0;
        let blueValue = CGFloat(arc4random_uniform(255)) / 255.0;
        let alphaValue = randomAlpha ? CGFloat(arc4random_uniform(255)) / 255.0 : 1;

        return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: alphaValue)
    }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_* BS 5

你可以用这种方式,

NSInteger aRedValue = arc4random()%255;
NSInteger aGreenValue = arc4random()%255;
NSInteger aBlueValue = arc4random()%255;

UIColor *randColor = [UIColor colorWithRed:aRedValue/255.0f green:aGreenValue/255.0f blue:aBlueValue/255.0f alpha:1.0f];
Run Code Online (Sandbox Code Playgroud)