点赞动画 iOS自带了粒子引擎的类 CAEmitterLayer ,是一个粒子发射器系统,每个粒子都是 CAEmitterCell 的实例。可以查看它们分别有什么属性。 有两个小点,一个是 CAEmitterLayer 一些属性对 CAEmitterCell 有成倍作用,如 birthRate ;另一个是没有明确的停止动画的方法,包括它的父类也没提供。可以想到的方法,除了把 layer 抹除掉之外,还可以将 CAEmitterLayer 的 birthRate 设置为0,这样每个 CAEmitterCell 的诞生速率都为0,就不会有动画了。 class PraiseEmitterView: UIView { private var timer: NSTimer? private let emitter: CAEmitterLayer! = { let emitter = CAEmitterLayer() return emitter }() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { emitter.frame = bounds emitter.birthRate = 0 emitter.emitterShape = kCAEmitterLayerLine emitter.emitterPosition = CGPointMake(0,CGRectGetHeight(bounds)) emitter.emitterSize = bounds.size emitter.emitterCells = [getEmitterCell(UIImage(named: "comment")!.CGImage!), getEmitterCell(UIImage(named: "flower_15")!.CGImage!)] self.layer.addSublayer(emitter) } func timeoutSelector() { emitter.birthRate = 0 } func emit() { emitter.birthRate = 2 timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(timeoutSelector), userInfo: nil, repeats: false) } private func getEmitterCell(contentImage: CGImage) -> CAEmitterCell { let emitterCell = CAEmitterCell() emitterCell.contents = contentImage emitterCell.lifetime = 2 emitterCell.birthRate = 2 emitterCell.yAcceleration = -70.0 emitterCell.xAcceleration = 0 emitterCell.velocity = 20.0 emitterCell.velocityRange = 200.0 emitterCell.emissionLongitude = CGFloat(0) emitterCell.emissionRange = CGFloat(M_PI_4) emitterCell.scale = 0.8 emitterCell.scaleRange = 0.8 emitterCell.scaleSpeed = -0.15 emitterCell.alphaRange = 0.75 emitterCell.alphaSpeed = -0.15 return emitterCell } }
时间: 2024-10-18 15:17:45