mardi 2 juillet 2019

How to properly generate a random gradient background?

I've been trying to create a function that generates a random gradient background every time a new view controller is presented, as shown with the code provided below, yet I'm unable to get it to properly work. The issue being that the "random" colors are always the same and are generated in the same order.

import Foundation

import UIKit

extension UIView {

    func setGradientBackground() {

        let redValue = CGFloat(drand48())
        let greenValue = CGFloat(drand48())
        let blueValue = CGFloat(drand48())

        let redValue2 = CGFloat(drand48())
        let greenValue2 = CGFloat(drand48())
        let blueValue2 = CGFloat(drand48())

        let random = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1).cgColor
        let random2 = UIColor(red: redValue2, green: greenValue2, blue: blueValue2, alpha: 1).cgColor

        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = [random, random2]

        return layer.insertSublayer(gradient, at: 0)
    }
}




Aucun commentaire:

Enregistrer un commentaire