Swift UIView.animateKeyFramesWithDuration未平滑设置动画
我正试着写一个闪烁的动画,但感觉时机不对。我在操场上做了一个简单的版本:Swift UIView.animateKeyFramesWithDuration未平滑设置动画,swift,uikit,uiviewanimation,Swift,Uikit,Uiviewanimation,我正试着写一个闪烁的动画,但感觉时机不对。我在操场上做了一个简单的版本: import UIKit import XCPlayground let v = UIView() v.frame.size = CGSize(width: 200, height: 200) v.backgroundColor = UIColor.redColor() v.layer.cornerRadius = 100 UIView.animateKeyframesWithDuration(1, delay: 0,
import UIKit
import XCPlayground
let v = UIView()
v.frame.size = CGSize(width: 200, height: 200)
v.backgroundColor = UIColor.redColor()
v.layer.cornerRadius = 100
UIView.animateKeyframesWithDuration(1, delay: 0, options: .Repeat, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.5, animations: {
v.alpha = 0.0
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
v.alpha = 0.5
})
}, completion: nil)
XCPlaygroundPage.currentPage.liveView = v
视图将从0淡入0.5,然后在恢复动画之前以全alpha显示一秒钟。我在模拟器里也注意到了同样的事情
关于关键帧的工作原理,我有什么遗漏吗?经过检查,我认为
v
视图的alpha
默认值为1.0
。这意味着在动画结束一秒钟后,它将再次处于满alpha
,然后动画将重复。为了补偿这种情况并获得您想要的效果,您可以考虑在运行<代码> xcPraseBoop.CurrutPaul.LiVeVIEW=V.P/>之前,将其<代码> Alpha < /代码>设置为<代码> 0代码>代码>。
更新:
//Import Statements
//Configuration and Initialization of v view
v.alpha = 0.5 //<--- This is the key point
UIView.animateKeyframesWithDuration(1, delay: 0, options: .Repeat, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.5, animations: {
v.alpha = 0.0
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
v.alpha = 0.5
})
}, completion: nil)
XCPlaygroundPage.currentPage.liveView = v
可以将代码中的动画分解为4种状态
alpha
是1.0
alpha
更改为0.0
alpha
更改为0.5
v
视图恢复为状态1,然后重复动画李>
状态4是出现满alpha
闪烁的地方,因为v
视图在0.0
秒内从0.5
变为1.0
。但是,计算机无法在0.0
秒内完成任何操作(由于复杂的物理原因,实际上不可能),因此当计算机试图尽可能接近0.0
秒时,结果是瞬间出现完整的alpha
为了避免这种情况,您可以将原始的alpha
设置为0.5
,这样动画的状态1将与其状态3的结果相同,或者您可以添加另一个关键帧,在动画结束之前将alpha
恢复到0.0
:
示例:
选项1:
//Import Statements
//Configuration and Initialization of v view
v.alpha = 0.5 //<--- This is the key point
UIView.animateKeyframesWithDuration(1, delay: 0, options: .Repeat, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.5, animations: {
v.alpha = 0.0
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
v.alpha = 0.5
})
}, completion: nil)
XCPlaygroundPage.currentPage.liveView = v
//导入语句
//v视图的配置和初始化
v、 alpha=0.5//我知道原来的alpha是1。我想知道为什么它会在重复之间回复到那个值。我发现这种行为令人惊讶。我知道动画完成后会被删除,基本上就是这样吗?有什么办法可以避免吗?@ThomasAbend请查看我的更新以获得改进的解释和可能的解决方案。