雪花效果
需要:一張你想展示的圖,這里我采用的是一張雪花的原圖,名字叫2.
效果:讓界面產(chǎn)生雪花飛舞的效果
實質(zhì):通過系統(tǒng)自帶的CAEmitterLayer與CAEmitterCell來產(chǎn)生高度隘弊、大小拙吉、顏色、速度之宿、方向豪筝、透明度都不同的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產(chǎn)生位置
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
// 每秒產(chǎn)生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.尺寸(本身大小的倍數(shù))
emitterCell.scale = 0.8
// 范圍:(0 --- 1.6)
emitterCell.scaleRange = 0.8
// 逐漸變小
emitterCell.scaleSpeed = -0.15
// 4.添加到emitter
emitter.emitterCells = [emitterCell]
}
}