swift 实现漂亮的粒子效果CAEmitterLayer


一些粒子效果

我们经常会在一些游戏或者应用中看到一些炫酷的粒子效果,我们在iOS中也能很轻松的搞一些粒子效果

我们本次做得是一个下雪的效果,看下效果图

源码地址:  https://github.com/smalldu/IOS-Animations
中的AnimationDemo10

下雪效果

这个 gif 录的有点卡 , 但是运行效果一点都不卡 很唯美。

iOS中的粒子效果是用CAEmitterLayer和CAEmitterCell 实现的 , 对cell的粒子数 ,存活时间。。。各种东西进行配置就可以了

常用的产生粒子模式 三种kCAEmitterLayerPoint 点 kCAEmitterLayerLine线 kCAEmitterLayerRectangle 矩形,大家可以自己试试 。我就不一一展示了。

下面是所有代码 ,代码量很少 。而且都有注释

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad() let rect = CGRect(x: 0.0, y: -70.0, width: view.bounds.width, height: 50.0) let emitter = CAEmitterLayer() emitter.frame = rect view.layer.addSublayer(emitter) emitter.emitterShape = kCAEmitterLayerRectangle //kCAEmitterLayerPoint //kCAEmitterLayerLine //kCAEmitterLayerRectangle emitter.emitterPosition = CGPointMake(rect.width/2, rect.height/2) emitter.emitterSize = rect.size let emitterCell = CAEmitterCell() emitterCell.contents = UIImage(named: "xh")!.scaleImageToWidth(30).CGImage emitterCell.birthRate = 120 //每秒产生120个粒子 emitterCell.lifetime = 3 //存活1秒 emitterCell.lifetimeRange = 3.0 emitter.emitterCells = [emitterCell] //这里可以设置多种粒子 我们以一种为粒子 emitterCell.yAcceleration = 70.0 //给Y方向一个加速度 emitterCell.xAcceleration = 20.0 //x方向一个加速度 emitterCell.velocity = 20.0 //初始速度 emitterCell.emissionLongitude = CGFloat(-M_PI) //向左 emitterCell.velocityRange = 200.0 //随机速度 -200+20 --- 200+20 emitterCell.emissionRange = CGFloat(M_PI_2) //随机方向 -pi/2 --- pi/2 //emitterCell.color = UIColor(red: 0.9, green: 1.0, blue: 1.0, // alpha: 1.0).CGColor //指定颜色 emitterCell.redRange = 0.3 emitterCell.greenRange = 0.3 emitterCell.blueRange = 0.3 //三个随机颜色 emitterCell.scale = 0.8 emitterCell.scaleRange = 0.8 //0 - 1.6 emitterCell.scaleSpeed = -0.15 //逐渐变小 emitterCell.alphaRange = 0.75 //随机透明度 emitterCell.alphaSpeed = -0.15 //逐渐消失 // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }

OK!搞定!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值