一、粒子发射器
在UIKit中,粒子系统由两部分组成:
- CAEmitterLayer :发射的层,主要控制粒子的形状和发射的位置(例如,在矩形内,或边缘)。这个层具有全局的乘法器,可以施加到系统内的CAEmitterCells。
- CAEmitterCell :单个粒子的原型。当散发出一个粒子,UIKit根据这个发射粒子和定义的基础上创建一个随机粒子。此原型包括一些属性来控制粒子的图片,颜色,方向,运动,缩放比例和生命周期。
CAEmitterLayer 继承自CALayer,提供了一个基于Core Animation的粒子发射系统,粒子用CAEmitterCell来初始化,一个单独的CAEmitterLayer可同时支持多个CAEmitterCell。
二、CAEmitterLayer 与 CAEmitterCell 重要属性
- CAEmitterLayer 属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| var emitterPosition: CGPoint
var emitterSize: CGSize
var emitterMode: String
var emitterShape: String
|
- CAEmitterCell 属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| var birthRate: Float
var lifetime: Float
var lifetimeRange: Float
var velocity: CGFloat var velocityRange: CGFloat
var emissionLongitude: CGFloat var emissionRange: CGFloat
var xAcceleration: CGFloat var yAcceleration: CGFloat var zAcceleration: CGFloat
var scale: CGFloat var scaleRange: CGFloat var scaleSpeed: CGFloat
var spin: CGFloat var spinRange: CGFloat
var color: CGColor? var redRange: Float var greenRange: Float var blueRange: Float var alphaRange: Float
|
三、雪花效果实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import UIKit
class SnowView: UIView { fileprivate lazy var snowEmitter = CAEmitterLayer()
override init(frame: CGRect) { super.init(frame: frame) snowEmitter.emitterPosition = CGPoint(x: bounds.width * 0.5, y: 0) snowEmitter.emitterSize = bounds.size snowEmitter.emitterMode = kCAEmitterLayerOutline snowEmitter.emitterShape = kCAEmitterLayerLine } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func snow() { let snowflake = CAEmitterCell() snowflake.name = "snow" snowflake.birthRate = 4 snowflake.lifetime = 50 snowflake.velocity = 10 snowflake.velocityRange = 10 snowflake.yAcceleration = 20 snowflake.emissionRange = 0.5 * .pi snowflake.spinRange = 0.3 * .pi snowflake.contents = UIImage(named: "snow")?.cgImage snowflake.scaleRange = 0.5 snowflake.color = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1).cgColor snowflake.redRange = 0.5 snowflake.greenRange = 0.5 snowflake.blueRange = 0.5 snowflake.alphaSpeed = -0.01 snowEmitter.emitterCells = [snowflake] layer.insertSublayer(snowEmitter, at: 0) } }
|