/// 获取随机颜色
let color = UIColor(red: CGFloat(randomIn(0, max: 255))/255.0, green: CGFloat(randomIn(0, max: 255))/255.0, blue: CGFloat(randomIn(0, max: 255))/255.0, alpha: 1.0)
self.view.backgroundColor = color
//定义渐变的颜色,多色渐变太魔性了,我们就用两种颜色
let topColor = UIColor(red: (CGFloat(randomIn(50, max: 205))/255.0), green: (CGFloat(randomIn(50, max: 205))/255.0), blue: (CGFloat(randomIn(50, max: 205))/255.0), alpha: 1)
//将颜色和颜色的位置定义在数组内
let gradientColors: [CGColor] = [topColor.CGColor, color.CGColor]
let gradientLocations: [CGFloat] = [0.0, 1.0]
//创建CAGradientLayer实例并设置参数
let gradientLayer: CAGradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
//设置其frame以及插入view的layer
gradientLayer.frame = self.view.frame
self.view.layer.insertSublayer(gradientLayer, atIndex: 0)
/**
获取随机函数
- parameter min: 最小值
- parameter max: 最大值
- returns: 返回随机数
*/
func randomIn(min: Int, max: Int) -> Int {
return Int(arc4random()) % (max - min + 1) + min
}
网友评论