如何使用Swift制作随机颜色

时间:2015-04-21 17:24:52

标签: swift random colors uicolor func

如何使用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

    }
}

11 个答案:

答案 0 :(得分:150)

您需要一个函数来生成0到1范围内的随机CGFloat

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)
    }
}

如果你想要一个随机的alpha,只需为它创建另一个随机数。

您现在可以像这样分配视图的背景颜色:

self.view.backgroundColor = .random()

答案 1 :(得分:44)

对于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

答案 2 :(得分:28)

创建一个生成随机颜色的函数:

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()

答案 3 :(得分:9)

使用 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)
  }
}

还有更多详情here

答案 4 :(得分:7)

Swift 4.2

我之所以添加这个答案,是因为它使用了不同的方法,并且因为许多以前的答案都需要附加的语法糖,我认为这不应该被优先考虑。香草雨燕获得胜利。

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)
    }
}

答案 5 :(得分:6)

SwiftUI-Swift 5

import SwiftUI

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

用法:

let randomColor: Color = .random

答案 6 :(得分:4)

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 :(得分:4)

Swift 5.1

执行此功能并生成随机颜色。

例如view.backgroundColor = random()

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

答案 8 :(得分:1)

对于随机纯色,您可以使用UIColor HSB初始化程序并仅对色相进行随机化:

t = 0:0.001:40;

W = [1/16, 1/8, 1/4, 1/2, 1, 15/8, 2, 5/2, 3, 4]*pi;

%Fill X with 10 rows (X(1, :) matches x1, X(2, :) matches x2...)
X = cos(W'*t);

%Plot using a for loop
for i = 1:10
    subplot(2,5,i);
    plot(t, X(i, :));
end

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

enter image description here

答案 9 :(得分:0)

UISupportedInterfaceOrientations~ipad

答案 10 :(得分:0)

使用带有内联函数的扩展名生成随机数

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)
    }
}