我需要CALayer
在指定时间在屏幕上显示一些CAAnimation
(例如 fadeIn )。我想让它在屏幕上停留几秒钟,然后用fadeOut
动画消失。
示例:如果我有一个timeRange:
CMTimeRangeMake(start: 3 , end : 5)
我需要在3秒开始时CAAnimation
,在5秒结束时需要一个。{CALayer必须仅在timeRange
期间出现。
我找到了一个显示CALayer
的工作,以便它在指定的时间出现,但我不知道如何让它停留一段时间。
// Call this method in viewDidLoad for quick demo
func layerAnimation(){
let box = CALayer()
box.frame = CGRect(x:100, y: 100, width: 100, height: 100)
box.backgroundColor = UIColor.orange.cgColor
self.view.layer.addSublayer(box)
// Animation
CATransaction.begin()
let hide = CABasicAnimation(keyPath: "opacity")
hide.duration = 3 // The Start time for the box to appear in seconds
hide.fromValue = 0
hide.toValue = 0
hide.isRemovedOnCompletion = false
hide.fillMode = kCAFillModeBoth
CATransaction.setCompletionBlock({() -> Void in
let fadeInFadeOut = CABasicAnimation(keyPath: "opacity")
fadeInFadeOut.duration = 0
fadeInFadeOut.fromValue = 0
fadeInFadeOut.toValue = 1
fadeInFadeOut.isRemovedOnCompletion = false
fadeInFadeOut.fillMode = kCAFillModeBoth
fadeInFadeOut.autoreverses = true
box.add(fadeInFadeOut, forKey: "fadeInFadeOut")
})
box.add(hide, forKey: "hide")
CATransaction.commit()
}
我最终希望能够为视频添加标题以制作像this one这样的歌词视频。
答案 0 :(得分:0)
如果我理解你是正确的,你希望动画延迟3秒,淡入然后在完全不透明度下显示2秒后淡出。如果它应该立即淡出,只需删除完成块内的开始时间设置。试一试。我正在使用beginTime属性,并且我也删除了isRemovedOnCompletion,因为您通常应该尽量避免使用它,因为您不想污染presentationLayer。我将实际动画持续时间更改为0.5秒。这是完全淡出我们需要多长时间。如果你想把它改成更长的东西,你可以。
// Call this method in viewDidAppear <-//Please for quick demo
func layerAnimation(){
let box = CALayer()
box.frame = CGRect(x:100, y: 100, width: 100, height: 100)
box.backgroundColor = UIColor.orange.cgColor
self.view.layer.addSublayer(box)
// Animation
CATransaction.begin()
let fadeIn = CABasicAnimation(keyPath: "opacity")
fadeIn.duration = 0.5
fadeIn.beginTime = CACurrentMediaTime() + 3.0 // The Start time for the box to appear in seconds
fadeIn.fromValue = 0
fadeIn.toValue = 1
//makes the animation start from the from value when there is a delay
fadeIn.fillMode = kCAFillModeBackwards
CATransaction.setCompletionBlock({() -> Void in
let fadeOut = CABasicAnimation(keyPath: "opacity")
fadeOut.duration = 0.5
fadeOut.beginTime = CACurrentMediaTime() + 2.0 // The Start time for the box to appear in seconds
fadeOut.fromValue = 1
fadeOut.toValue = 0
//makes the animation start from the from value when there is a delay
fadeOut.fillMode = kCAFillModeBackwards
box.add(fadeOut, forKey: "hide")
//update the model so that it is really hidden. best not to use isRemovedOnCompletion
box.opacity = 0
})
box.add(fadeIn, forKey: "show")
CATransaction.commit()
}