簡體   English   中英

創建一個垂直CAEmitterLayer

[英]creating a vertical CAEmitterLayer

我正在創建一個CAEmitterLayer,它是屏幕的高度,然后推出-X,所以CAEmitterCells從左邊(屏幕外)移動到右上角。

我遇到的問題是忽略了CAEmitterLayer的emitterSize height屬性。 這導致所有單元格從單個點發出,而不是使用emitterSize設置的單元格。

這是發射器:

emitter.emitterPosition = CGPoint(x: -50, y: (view.frame.height / 2))
emitter.emitterShape = kCAEmitterLayerLine
emitter.emitterSize = CGSize(width: 2, height: view.frame.height)

我提到emitterSize 高度不起作用,因為如果我改變上面的emitterSize的寬度,我可以看到寬度正確改變! 無論我為高度賦予什么價值......它都被忽略了。

和CAEmitterCells

cell.birthRate = 10
cell.lifetime = 10
cell.velocity = CGFloat(50)
cell.emissionLongitude = (45 * (.pi/180))

如何將emitterSize寬度設置為2點寬和視圖的高度?

kCAEmitterLayerLine始終是零厚度的水平線。 僅使用emitterSize.width

通過將發射器層的變換設置為旋轉,可以垂直使用線形。 游樂場示例:

import UIKit
import PlaygroundSupport

class VerticalEmitterView: UIView {

    let emitter = CAEmitterLayer()

    override func layoutSubviews() {
        super.layoutSubviews()

        let bounds = self.bounds
        emitter.position = CGPoint(x: bounds.midX, y: bounds.midY)
        emitter.bounds = CGRect(x: 0, y: 0, width: bounds.size.height, height: bounds.size.width)
        emitter.emitterPosition = CGPoint(x: bounds.width / 2, y: -50)
        emitter.emitterSize = CGSize(width: emitter.bounds.size.width, height: 0)

        if emitter.superlayer != self.layer {
            emitter.setAffineTransform(CGAffineTransform(rotationAngle: -.pi / 2))
            emitter.emitterShape = kCAEmitterLayerLine

            let cell = CAEmitterCell()
            cell.birthRate = 100
            cell.lifetime = 10
            cell.velocity = 50
            cell.emissionLongitude = .pi
            cell.color = UIColor.red.cgColor
            let particleSize = CGSize(width: 5, height: 5)
            let image = UIGraphicsImageRenderer(size: particleSize).image(actions: { (rc) in
                UIColor.white.setFill()
                let gc = UIGraphicsGetCurrentContext()
                UIBezierPath(ovalIn: CGRect(origin: .zero, size: particleSize)).fill()
            })
            cell.contents = image.cgImage
            emitter.emitterCells = [cell]

            layer.addSublayer(emitter)
        }
    }

}

let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
rootView.backgroundColor = .white
let emitterView = VerticalEmitterView(frame: rootView.bounds)
rootView.addSubview(emitterView)
PlaygroundPage.current.liveView = rootView

結果:

發射器演示

(不連續性是因為這個GIF是一秒鍾的循環。)

我有完全相同的問題。 通過Apple的文檔,看起來如果發射器形狀是kCAEmitterLayerLine,它會忽略發射器的高度。

我找到的不太理想的解決方法是使用一個足夠大的kcaEmitterLayerRectangle,以便矩形的一邊是你想要的線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM