iOS实现爆炸的粒子效果示例代码

2020-01-18 16:22:24于海丽

protocol ExplosionAnimationProtocol {

 // 粒子初始位置
 var oldPosition: CGPoint { set get }

 // 粒子最终位置
 var newPosition: CGPoint { set get }

 // 缩放
 var scale: CGFloat { set get }

 // 动画时长
 var duration: CFTimeInterval { set get }

 // 动画重复次数
 var repeatCount: Float { set get }

 // 生成动画
 func animation() -> CAAnimation

 // 设置动画完之后的属性
 func resetLayerProperty(layer: CALayer)
}

要发生爆炸view的动画效果

这个比较简单,就是上下左右震动下。具体代码就不贴出来了。


let shakeAnimation = CAKeyframeAnimation(keyPath: "position")
...

代码结构

大致思路就是这样。代码结构如下:

ios,爆炸的粒子效果,爆炸效果,ios粒子效果

    ExplosionLayer是粒子的父容器,

    ExplosionPointLayer是粒子本身

    ExplosionHelper是个辅助类,用于计算粒子位置,颜色值。

    FallAnimationUpAnimation是实现了ExplosionAnimationProtocol的动画,分别提供向下落,向上的效果。

碰到的问题

刚开始我是在边计算颜色值,边绘制粒子,发现会卡一下才会有爆炸效果出来,分析可能是在计算颜色值在主线程,时间较长,所以卡住了。

后来想到放到后台线程中去做,但是在主线程中取色值的时候,后台必须执行完,所以用了信号量来进行同步。


// 震动效果
private func shake() {

  self.createSemaphore()

  // 计算位置,色值
  self.caculate()

  let shakeAnimation = CAKeyframeAnimation(keyPath: "position")

  shakeAnimation.values = [NSValue.init(CGPoint: self.position), NSValue.init(CGPoint: CGPointMake(self.position.x, self.position.y + 1)), NSValue.init(CGPoint: CGPointMake(self.position.x + 1, self.position.y - 1)), NSValue.init(CGPoint: CGPointMake(self.position.x - 1, self.position.y + 1))]

  shakeAnimation.duration = 0.2
  shakeAnimation.repeatCount = 15
  shakeAnimation.delegate = self
  shakeAnimation.removedOnCompletion = true

  self.targetView?.layer.addAnimation(shakeAnimation, forKey: "shake")
 }

当要爆炸的view开始震动时,就开始在后台计算。震动动画结束后,等待计算完成。


override func animationDidStop(anim: CAAnimation, finished flag: Bool) {

  // wait for caculate
  dispatch_semaphore_wait(self.semaphore!, DISPATCH_TIME_FOREVER)

  print("shake animation stop")

  // begin explode
  if let targetView = self.targetView {
   self.parentLayer?.addSublayer(self)
   ExplosionHelper.createExplosionPoints(self, targetView: targetView, animationType: self.animationType)

   self.targetView?.hidden = true
  }
 }