如何使用 Swift 制作随机颜色 [英] How to make a random color with Swift

查看:22
本文介绍了如何使用 Swift 制作随机颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Swift 生成随机颜色函数?

How I can make a random color function using 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

    }
}

推荐答案

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

You're going to need a function to produce random CGFloats in the range 0 to 1:

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

然后您可以使用它来创建随机颜色:

Then you can use this to create a random colour:

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

如果您想要一个随机 alpha,也只需为此创建另一个随机数.

If you wanted a random alpha, just create another random number for that too.

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

You can now assign your view's background colour like so:

self.view.backgroundColor = .random()

这篇关于如何使用 Swift 制作随机颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆