【问题标题】:EmitterCells not showing in CAEmitterLayerEmitterCells 未显示在 CAEmitterLayer 中
【发布时间】:2020-12-01 23:04:00
【问题描述】:

我似乎无法获得 CAEmitterLayer 显示 CAEmitterCells。我在 Storyboard 中添加了 ConfettiEmitterView,并且视图按预期显示为红色背景。但细胞没有显示。也没有错误或警告。

代码:

import UIKit

class ConfettiEmitterView: UIView {

override class var layerClass:AnyClass {
    return CAEmitterLayer.self
}

func makeEmmiterCell(color:UIColor, velocity:CGFloat, scale:CGFloat)-> CAEmitterCell {
    let cell = CAEmitterCell()
    cell.birthRate = 10
    cell.lifetime = 20.0
    cell.lifetimeRange = 0
    cell.velocity = velocity
    cell.velocityRange = velocity / 4
    cell.emissionLongitude = .pi
    cell.emissionRange = .pi / 8
    cell.scale = scale
    cell.scaleRange = scale / 3
    cell.contents = roundImage(with: .yellow)
    return cell
}

override func layoutSubviews() {
    let emitter = self.layer as! CAEmitterLayer
    emitter.frame = self.bounds
    emitter.masksToBounds = true
    emitter.emitterShape = .line
    emitter.emitterPosition = CGPoint(x: bounds.midX, y: 0)
    emitter.emitterSize = CGSize(width: bounds.size.width, height: 1)
    
    emitter.backgroundColor = UIColor.red.cgColor // Setting the background to red
    
    let near = makeEmmiterCell(color: UIColor(white: 1, alpha: 1), velocity: 100, scale: 0.3)
    let middle = makeEmmiterCell(color: UIColor(white: 1, alpha: 0.66), velocity: 80, scale: 0.2)
    let far = makeEmmiterCell(color: UIColor(white: 1, alpha: 0.33), velocity: 60, scale: 0.1)
    
    emitter.emitterCells = [near, middle, far]
}

func roundImage(with color: UIColor) -> UIImage {
        let rect = CGRect(origin: .zero, size: CGSize(width: 12.0, height: 12.0))
        return UIGraphicsImageRenderer(size: rect.size).image { context in
            context.cgContext.setFillColor(color.cgColor)
            context.cgContext.addPath(UIBezierPath(ovalIn: rect).cgPath)
            context.cgContext.fillPath()
        }
    }

}

向 Storyboard 中的 UIViewController 添加一个 ConfettiEmitterView 类型的视图应该足以重新创建问题。

【问题讨论】:

    标签: swift xcode swift5 ios14 caemitterlayer


    【解决方案1】:

    改变

    cell.contents = roundImage(with: .yellow)
    

    cell.contents = roundImage(with: .yellow).cgImage
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多