我试着给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];但颜色总是黑色的。怎么啦?
发布于 2014-01-15 06:28:38
因为您已将颜色值分配给int变量。使用float (或CGFloat)代替。另外(作为@stackunderflow's said),为了覆盖整个范围的0.0 ... 1.0,剩余部分必须采用模256。
CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;发布于 2014-05-07 15:02:36
[UIColor colorWithHue:drand48() saturation:1.0 brightness:1.0 alpha:1.0];或者在Swift:
UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)随意随意调整饱和度和亮度以满足你的喜好。
发布于 2016-01-06 22:31:51
下面是一个快速版本,它被制成了一个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)
}
}https://stackoverflow.com/questions/21130433
复制相似问题