练习:粒子发射器

2021-08-26  本文已影响0人  一个栗
import UIKit

protocol Emitterable {
    
}

extension Emitterable where Self : UIViewController {
    func startEmittering(_ point : CGPoint) {
        // 1 创建发射器
        let emitter = CAEmitterLayer()
        // 2.设置发射器的位置
        emitter.emitterPosition = point
        // 3.开启三维效果
        emitter.preservesDepth = true
        // 4.创建粒子并设置粒子相关属性
        var cells = [CAEmitterCell]()
        for i in 0..<10 {
            // 4.1 创建粒子cell
            let cell = CAEmitterCell()
            // 4.2 设置粒子速度
            cell.velocity = 150
            cell.velocityRange = 100
            // 4.3 设置粒子的大小
            cell.scale = 0.7
            cell.scaleRange = 0.3
            // 4.4 设置粒子的方向
            cell.emissionLongitude = CGFloat(-(Double.pi) / 2)
            cell.emissionRange = CGFloat((Double.pi / 2) / 6)
            // 4.5 设置粒子存活时间
            cell.lifetime = 3
            cell.lifetimeRange = 1.5
            // 4.6 设置粒子旋转
            cell.spin = CGFloat(Double.pi / 2)
            cell.spinRange = CGFloat((Double.pi / 2) / 2)
            // 4.7 设置粒子每秒弹出的个数
            cell.birthRate = 2
            // 4.8 设置粒子展示的图片good7_30x30
            cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
            // 4.9 添加到数组中
            cells.append(cell)
        }
        // 5. 将粒子设置到发射器中
        emitter.emitterCells = cells
        // 6. 将发射器的layer添加到父layer中
        view.layer.addSublayer(emitter)
    }
    func stopEmittering() {
        view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer()
    }
}
import UIKit

class ViewController: UIViewController, Emitterable {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton.init(type: .custom)
        button.frame = CGRect(x: 100, y: 700, width: 175, height: 50)
        button.setTitle("start", for: UIControl.State.normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 30)
        button.setTitleColor(UIColor.blue, for: UIControl.State.normal)
        button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
        view .addSubview(button)
    }
    
    @objc func tapped(sender: UIButton) {
        sender.isSelected = !sender.isSelected;
        if sender.currentTitle == "start" {
            sender.setTitle("stop", for: UIControl.State(rawValue: 0))
        } else {
            sender.setTitle("start", for: UIControl.State(rawValue: 0))
        }
        let point = CGPoint(x: sender.center.x, y: sender.center.y)
        sender.isSelected ? startEmittering(point) : stopEmittering()
    }
}
上一篇下一篇

猜你喜欢

热点阅读