微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

子类化 CALayer 会破坏动画

如何解决子类化 CALayer 会破坏动画

尝试在 1.5 秒内进行简单的 opacity 淡入/淡出。 (0.5 秒,1 秒)。

如果我将通用 CAShapeLayer 添加UIView 并在那里完成我的所有绘图,它会起作用。

如果我将 CAShapeLayer 子类化并在那里进行绘图,则 CATranscation.setAnimationDuration(_:) 块不遵守持续时间并快速执行。此外,有时它会反转不透明度!

实现一:直接从内部视图绘制

class Implemention1: UIView {
    
    let shapeLayer = CAShapeLayer()
        
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.setup()
    }
    
    func setup() {
        self.layer.insertSublayer(self.shapeLayer,at: 0)
        self.shapeLayer.opacity = 0
        self.shapeLayer.fillColor = UIColor.red.cgColor
        self.shapeLayer.frame = self.bounds
        self.shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath
    }
    
    func fadeOpacticityInOut() {
        CATransaction.begin()
        CATransaction.setAnimationDuration(0.5)
        CATransaction.setCompletionBlock {
            CATransaction.begin()
            CATransaction.setAnimationDuration(1.0)
            self.shapeLayer.opacity = 0
            CATransaction.commit()
        }
        self.shapeLayer.opacity = 1
        CATransaction.commit()
    }
}    

实现 2:子类化 CAShapeLayer 并或多或少地做同样的事情。

class Implementation2: UIView {
    
    let shapeLayer = FadeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.setup()
    }
    
    func setup() {
        self.layer.insertSublayer(self.shapeLayer,at: 0)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.shapeLayer.frame = self.bounds
        self.shapeLayer.setNeedsdisplay()
    }
    
    
    func fadeOpactiyInOut() {
        self.shapeLayer.fadeOpacticityInOut()
    }
    
}

class FadeLayer: CAShapeLayer {
    
    override init(layer: Any) {
        super.init(layer: layer)
        self.setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.setup()
    }
    
    override init() {
        super.init()
        self.setup()
    }
    
    func setup() {
        self.opacity = 0
        self.fillColor = UIColor.red.cgColor
    }
    
    func fadeOpacticityInOut() {
        CATransaction.begin()
        CATransaction.setAnimationDuration(0.5)
        CATransaction.setCompletionBlock {
            CATransaction.begin()
            CATransaction.setAnimationDuration(1.0)
            self.opacity = 0
            CATransaction.commit()
        }
        self.opacity = 1
        CATransaction.commit()
    }
    
    override func display() {
        self.path = UIBezierPath(rect: self.bounds).cgPath
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。