仅运行一次CAEmitterLayer

i1icjdpr  于 2022-10-31  发布在  Swift
关注(0)|答案(2)|浏览(61)

我只想运行一次CAEmitterLayer,我想停止birthRate,但我不能。我想让它在点击屏幕时只运行一次。我已经尝试了代理,但我不能让它工作。请告诉我我的代码是否有效。

import UIKit
    import PlaygroundSupport

    class Emitter {
        static func get(with image: UIImage) -> CAEmitterLayer {
            let emitter = CAEmitterLayer()
            emitter.emitterShape = kCAEmitterLayerLine
            emitter.emitterCells = generateEmitterCells(image: image)
            print("emit")
            emitter.setValue(0.0, forKey: "em")
            return emitter
        }

        static func generateEmitterCells(image: UIImage) -> [CAEmitterCell] {
            var cells = [CAEmitterCell]()
            let cell = CAEmitterCell()
            cell.contents = image.cgImage
            cell.birthRate = 0.1
            cell.lifetime = 20
            cell.velocity = 250
            cell.emissionRange = (10 * (.pi/180))
            cell.scale = 0.9
            cell.scaleRange = 0.3
            cell.velocityRange = 100
            cells.append(cell)
            print("cells")
            return cells
        }

    }

    class ViewController : UIViewController{
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))

            let view2 = UIView(frame: self.view.frame)

            self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 580)
            super.view.backgroundColor = UIColor.white
            self.view.addSubview(view2)
        }

        @objc func handleTap() {
            rain()
        }

        func rain() {
            let emitter = Emitter.get(with: UIImage(named: "Group 1493")!)
            emitter.emitterPosition = CGPoint(x: view.frame.width / 2, y: view.frame.height + 25)
            emitter.emitterSize = CGSize(width: view.frame.width, height: 2)
            self.view.layer.addSublayer(emitter)
        }

    }

    let controller = ViewController()
    PlaygroundPage.current.liveView = controller.view
drnojrws

drnojrws1#

您可以在第一次启动后将lifetime属性设置为0
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { emitter.lifetime = 0 }

gojuced7

gojuced72#

你需要做几件事。
1.您需要CAEmitterLayerbeginTimeemitter.beginTime = CACurrentMediaTime()
1.为了阻止新粒子的诞生,你需要设置emitter.birthRate = 0。你可以使用GCD来延迟它,以创建这种飞溅效果。

相关问题