我正在创建一个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 height 不起作用,因为如果我改变上面的emitterSize的宽度,我可以看到宽度正确变化!无论我为高度赋予什么价值......都会被忽略。
和CAEmitterCells
cell.birthRate = 10
cell.lifetime = 10
cell.velocity = CGFloat(50)
cell.emissionLongitude = (45 * (.pi/180))
如何将emitterSize宽度设置为2点宽和视图高度?
答案 0 :(得分: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是一秒钟的循环。)
答案 1 :(得分:0)
我有完全相同的问题。通过Apple的文档,看起来如果发射器形状是kCAEmitterLayerLine,它会忽略发射器的高度。
我发现不太理想的解决方法是使用一个足够大的kcaEmitterLayerRectangle,这样矩形的一边就是你想要的那条线。