How to make a random color with Swift

后端 未结 11 1538
甜味超标
甜味超标 2020-11-27 04:01

How I can make a random color function using Swift?

import UIKit

class ViewController: UIViewController {

    var randomNumber = arc4random_uniform(20)
            


        
相关标签:
11条回答
  • 2020-11-27 04:37

    Swift 4.2

    0 讨论(0)
  • 2020-11-27 04:43

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

    Usage:

    let randomColor: Color = .random

    0 讨论(0)
  • 2020-11-27 04:44

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

    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()
    
    0 讨论(0)
  • 2020-11-27 04:46

    Swift 4.2 Extension

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

    Usage:

    let color = UIColor.random()
    
    0 讨论(0)
  • 2020-11-27 04:46

    Using an extension with an inline function to generate randoms

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题