Создать случайный 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;
}
И используйте его:
[mat addAttributes:@{NSForegroundColorAttributeName : [self randomColor]} range:range];
Но цвет всегда черный. Что не так?
P.S. Извините за мой английский)
Ответы
Ответ 1
Потому что вы назначили значения цвета для переменных int
. CGFloat
этого используйте float
(или CGFloat
). Также (как @stackunderflow сказал), остаток должен быть принят по модулю 256, чтобы охватить весь диапазон 0.0... 1.0
:
CGFloat red = arc4random() % 256 / 255.0;
// Or (recommended):
CGFloat red = arc4random_uniform(256) / 255.0;
Ответ 2
[UIColor colorWithHue:drand48() saturation:1.0 brightness:1.0 alpha:1.0];
или в Swift:
UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)
Не стесняйтесь рандомизировать или настроить насыщенность и яркость по своему вкусу.
Ответ 3
попробуй это
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];
Ответ 4
Вот быстрая версия, сделанная в расширении 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)
}
}
Ответ 5
u может использовать этот способ,
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];
Ответ 6
// RGB
UIColor *randomRGBColor = [[UIColor alloc] initWithRed:arc4random()%256/256.0
green:arc4random()%256/256.0
blue:arc4random()%256/256.0
alpha:1.0];
// HSB
UIColor *randomHSBColor = [[UIColor alloc] initWithHue:arc4random()%256/256.0
saturation:(arc4random()%128/256.0)+0.5
brightness:(arc4random()%128/256.0)+0.5
alpha:1.0];
Ответ 7
arc4random() % 255 / 255.0
всегда будет усечен до 0, потому что arc4random()%255
будет целым числом от 0 до 254 включительно, а деление на 255,0 и кастинг на int всегда приведет к 0. Вы должны сохранить результат как float вместо.
(Также вы должны использовать arc4random()%256
, если вы хотите случайно выбирать из всех возможных цветов.)
Ответ 8
Вот фрагмент:
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
self.view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
Ответ 9
Быстрое решение с использованием класса var 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)
}
}
Используйте, как и любую другую встроенную переменную класса UIColor
(.red
, .blue
, .white
и т.д.), Например:
view.backgroundColor = .random
Ответ 10
Удаляет дублирование 3 строк arc4random
:)
static func randomColor() -> UIColor {
let random = {CGFloat(arc4random_uniform(255)) / 255.0}
return UIColor(red: random(), green: random(), blue: random(), alpha: 1)
}