问题描述
尝试在 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 (将#修改为@)