Подтвердить что ты не робот

Как сделать случайный цвет с помощью Swift

Как я могу сделать функцию случайного цвета, используя Swift?

import UIKit

class ViewController: UIViewController {

    var randomNumber = arc4random_uniform(20)
    var randomColor = arc4random()

    //Color Background randomly
    func colorBackground() {

        // TODO: set a random color
        view.backgroundColor = UIColor.yellow

    }
}
4b9b3361

Ответ 1

Вам понадобится функция для создания случайного CGFloat в диапазоне от 0 до 1:

extension CGFloat {
    static func random() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

Затем вы можете использовать это для создания случайного цвета:

extension UIColor {
    static func random() -> UIColor {
        return UIColor(red:   .random(),
                       green: .random(),
                       blue:  .random(),
                       alpha: 1.0)
    }
}

Если вам нужна случайная альфа, просто создайте еще одно случайное число для этого.

Теперь вы можете назначить цвет фона своего вида следующим образом:

self.view.backgroundColor = .random()

Ответ 2

Для Swift 4.2

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
}

Для Swift 3 и выше:

extension CGFloat {
    static var random: CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }
}

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random, green: .random, blue: .random, alpha: 1.0)
    }
}

Использование:

let myColor: UIColor = .random

Ответ 3

Сделайте функцию для генерации случайного цвета:

func getRandomColor() -> UIColor {
     //Generate between 0 to 1
     let red:CGFloat = CGFloat(drand48())   
     let green:CGFloat = CGFloat(drand48()) 
     let blue:CGFloat = CGFloat(drand48())  

     return UIColor(red:red, green: green, blue: blue, alpha: 1.0)
}

Теперь вы можете вызывать эту функцию всякий раз, когда вам нужен случайный цвет.

self.view.backgroundColor = getRandomColor()

Ответ 4

С Swift 4.2 вы можете упростить это, используя новые случайные функции, которые были добавлены:

extension UIColor {
  static func random () -> UIColor {
    return UIColor(
      red: CGFloat.random(in: 0...1),
      green: CGFloat.random(in: 0...1),
      blue: CGFloat.random(in: 0...1),
      alpha: 1.0)
  }
}

Есть более подробная информация здесь.

Ответ 5

Swift 4.2 🔸

Я добавляю этот ответ, потому что он использует другой подход, и потому что многие из предыдущих ответов требуют дополнительного синтаксического сахара, который, по моему мнению, не должен быть предпочтительным. Vanilla Swift для победы.

extension UIColor {
    /**
     * Returns random color
     * ## Examples: 
     * self.backgroundColor = UIColor.random
     */
    static var random: UIColor {
        let r:CGFloat  = .random(in: 0...1)
        let g:CGFloat  = .random(in: 0...1)
        let b:CGFloat  = .random(in: 0...1)
        return UIColor(red: r, green: g, blue: b, alpha: 1)
    }
}

Ответ 6

Расширение Swift 4.2

extension UIColor {

    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }

    convenience init(rgb: Int) {
        self.init(
            red: (rgb >> 16) & 0xFF,
            green: (rgb >> 8) & 0xFF,
            blue: rgb & 0xFF
        )
    }

    static func random() -> UIColor {
        return UIColor(rgb: Int(CGFloat(arc4random()) / CGFloat(UINT32_MAX) * 0xFFFFFF))
    }

}

Использование:

let color = UIColor.random()

Ответ 7

func anotherGetRandomColor()->UIColor{

    let newRed   = arc4random_uniform(255)/255
    let newGreen = arc4random_uniform(255)/255
    let newBlue  = arc4random_uniform(255)/255

    return UIColor(red: CGFloat(newRed), green: CGFloat(newGreen), blue: CGFloat(newBlue), alpha: 1.0)
}

Ответ 8

Использование расширения со встроенной функцией для генерации случайных событий

extension UIColor {
    static func random() -> UIColor {

        func random() -> CGFloat { return .random(in:0...1) }

        return UIColor(red:   random(),
                       green: random(),
                       blue:  random(),
                       alpha: 1.0)
    }
}

Ответ 9

Для случайных сплошных цветов вы можете использовать UIColor HSB initializer и рандомизировать только оттенок:

extension UIColor {
    static var random: UIColor {
        return  .init(hue: .random(in: 0...1), saturation: 1, brightness: 1, alpha: 1)
    }
}

let color1: UIColor = .random
let color2: UIColor = .random
let color3: UIColor = .random
let color4: UIColor = .random
let color5: UIColor = .random

enter image description here