- 創(chuàng)建一個 Swift file 文件殉疼,用協(xié)議實現(xiàn)粒子動畫的發(fā)射和停止效果
import UIKit
protocol Emitterable {
}
extension Emitterable where Self : UIViewController {
func startEmittering(_ point : CGPoint) {
// 1.創(chuàng)建發(fā)射器
let emitter = CAEmitterLayer()
// 2.設(shè)置發(fā)射器的位置
emitter.emitterPosition = point
// 3.開啟三維效果
emitter.preservesDepth = true
// 4.創(chuàng)建例子, 并且設(shè)置例子相關(guān)的屬性
var cells = [CAEmitterCell]()
for i in 0..<10 {
// 4.1.創(chuàng)建例子Cell
let cell = CAEmitterCell()
// 4.2.設(shè)置粒子速度
cell.velocity = 150
cell.velocityRange = 100
// 4.3.設(shè)置例子的大小
cell.scale = 0.7
cell.scaleRange = 0.3
// 4.4.設(shè)置粒子方向
cell.emissionLongitude = CGFloat(-M_PI_2)
cell.emissionRange = CGFloat(M_PI_2 / 6)
// 4.5.設(shè)置例子的存活時間
cell.lifetime = 3
cell.lifetimeRange = 1.5
// 4.6.設(shè)置粒子旋轉(zhuǎn)
cell.spin = CGFloat(M_PI_2)
cell.spinRange = CGFloat(M_PI_2 / 2)
// 4.6.設(shè)置例子每秒彈出的個數(shù)
cell.birthRate = 2
// 4.7.設(shè)置粒子展示的圖片
cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
// 4.8.添加到數(shù)組中
cells.append(cell)
}
// 5.將粒子設(shè)置到發(fā)射器中
emitter.emitterCells = cells
// 6.將發(fā)射器的layer添加到父layer中
view.layer.addSublayer(emitter)
}
func stopEmittering() {
/*
for layer in view.layer.sublayers! {
if layer.isKind(of: CAEmitterLayer.self) {
layer.removeFromSuperlayer()
}
}
*/
view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer()
}
}
- 使用方式(使用該效果的控制器验烧,需要先遵守該協(xié)議
Emitterable
)
開始 startEmittering(CGPoint(x: 200, y: 600))
停止 stopEmittering()
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者