CAEmitterLayer 在 Swift 的 MacOS 中不工作

CAEmitterLayer doesn't work in MacOS with Swift

我只是简单地创建了一个故事板程序,并将主要 ViewController 代码更改为下面的代码,该代码在其他人的示例中运行良好。但在视图中似乎什么都没有?寻求帮助。

我做了什么:

  1. 用故事板创建一个项目,我得到了 'AppDelegate.swift' 和 'ViewController.swift'

  2. 粘贴'Ball_green.png'到我的项目,在我的项目的文件树下可以看到。

  3. 将下面的代码粘贴到 'ViewController.swift'

import Cocoa

class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        self.view.wantsLayer = true
        self.addLayer()
    }
    
    func addLayer(){
        let rootLayer = self.view.layer
        let snowEmitter = CAEmitterLayer()
        snowEmitter.drawsAsynchronously = true
        snowEmitter.name = "snowEmitter"
        snowEmitter.zPosition = 10.0
        snowEmitter.emitterPosition = CGPoint(x: 0, y: 0)
        snowEmitter.renderMode = CAEmitterLayerRenderMode.backToFront
        snowEmitter.emitterShape = CAEmitterLayerEmitterShape.circle
        snowEmitter.emitterZPosition = -43.00
        snowEmitter.emitterSize = CGSize(width: 160, height: 160)
        snowEmitter.velocity = 20.57
        snowEmitter.emitterMode = CAEmitterLayerEmitterMode.points
        snowEmitter.birthRate = 10
        let snowFlakesCell2 = CAEmitterCell()
        snowFlakesCell2.emissionRange = .pi
        snowFlakesCell2.lifetime = 10.0
        snowFlakesCell2.birthRate = 4.0
        snowFlakesCell2.velocity = 2.0
        snowFlakesCell2.velocityRange = 100.0
        snowFlakesCell2.yAcceleration = 300.0
        snowFlakesCell2.contents = NSImage(named: "Ball_green.png")!.cgImage
        snowFlakesCell2.magnificationFilter = convertFromCALayerContentsFilter(CALayerContentsFilter.nearest)
        snowFlakesCell2.scale = 0.72
        snowFlakesCell2.scaleRange = 0.14
        snowFlakesCell2.spin = 0.38
        snowFlakesCell2.spinRange = 0
        snowEmitter.emitterCells = [snowFlakesCell2]
        rootLayer!.addSublayer(snowEmitter)
    }
}

fileprivate func convertFromCALayerContentsFilter(_ input: CALayerContentsFilter) -> String {
    return input.rawValue
}
extension NSImage {
    var cgImage: CGImage {
        get {
            let imageData = self.tiffRepresentation
            let source = CGImageSourceCreateWithData(imageData as! CFData, nil)
            let maskRef = CGImageSourceCreateImageAtIndex(source!, 0, nil)
            return maskRef!
        }
    }
}

添加代码后问题解决了