雪花效果
需要:一张你想展示的图,这里我采用的是一张雪花的原图,名字叫2.
效果:让界面产生雪花飞舞的效果
实质:通过系统自带的CAEmitterLayer与CAEmitterCell来产生高度、大小、颜色、速度、方向、透明度都不同的cell展示在界面上
图片效果:
代码详解:
import UIKit
class ViewController: UIViewController {
// 图层属性与cell属性
let emitter = CAEmitterLayer()
let emitterCell = CAEmitterCell()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(red: 89/255, green: 195/255, blue: 236/255, alpha: 1)
self.setEmitter()
self.setEmitterCell()
}
}
extension ViewController {
//MARK: - 图层
func setEmitter() {
//kCAEmitterLayerPoint:点
//kCAEmitterLayerLine:线
//kCAEmitterLayerRectangle:矩阵
emitter.emitterShape = kCAEmitterLayerRectangle
emitter.frame = CGRectMake(0, -75, 375, 50)
// emitter产生位置
emitter.emitterPosition = CGPointMake(self.view.bounds.width/2, 25)
emitter.emitterSize = CGSize.init(width: self.view.bounds.width, height: 50)
self.view.layer.addSublayer(emitter)
}
//MARK: - Cell
func setEmitterCell() {
// 0.粒子胞(图片)
emitterCell.contents = UIImage(named: "2")!.CGImage
// 每秒产生120个
emitterCell.birthRate = 120
// 初始存活时间
emitterCell.lifetime = 3
// 随机存活时间(0-6)
emitterCell.lifetimeRange = 3
// 1.速度
// 初始速度:范围(-200+20 --- 200+20)
emitterCell.velocity = 20
emitterCell.velocityRange = 200
// 速度方向:范围(-PI/2 --- PI/2)
emitterCell.emissionLongitude = CGFloat(-M_PI)
emitterCell.emissionRange = CGFloat(M_PI_2)
// 加速度:x和y两个方向
emitterCell.xAcceleration = 20
emitterCell.yAcceleration = 80
// 2.三个颜色变色范围:(0 --- 0.3)
emitterCell.redRange = 0.3
emitterCell.greenRange = 0.3
emitterCell.blueRange = 0.3
// 随机透明度:(0 --- 0.75)
emitterCell.alphaRange = 0.75
// 逐渐消失
emitterCell.alphaSpeed = -0.15
// 3.尺寸(本身大小的倍数)
emitterCell.scale = 0.8
// 范围:(0 --- 1.6)
emitterCell.scaleRange = 0.8
// 逐渐变小
emitterCell.scaleSpeed = -0.15
// 4.添加到emitter
emitter.emitterCells = [emitterCell]
}
}