gpt4 book ai didi

swift - UIView.animateKeyFramesWithDuration 动画不流畅

转载 作者:搜寻专家 更新时间:2023-11-01 07:22:35 24 4
gpt4 key购买 nike

我正在尝试编写一个闪烁的动画,但感觉时间不对。我在 Playground 上做了一个简单的版本:

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

View 从 0 淡化到 0.5,然后在恢复动画之前似乎以全 alpha 停顿了一秒钟。我在模拟器中注意到了同样的事情。

关于关键帧应该如何工作,我是否遗漏了什么?

最佳答案

经过检查,我相信您的 v View 的 alpha 的默认值是 1.0。这意味着在您的动画结束一瞬间后,它再次处于完整的 alpha 状态,然后重复动画。为了弥补这一点并获得您想要的效果,您可以考虑在运行 XCPlaygroundPage.currentPage.liveView = v 之前将其 alpha 设置为 0.0 .

更新:

您可以将代码中的动画分解为 4 种状态。

  1. 一开始,alpha1.0
  2. 第一个关键帧在 0.5 秒内将 alpha 更改为 0.0
  3. 第二个关键帧在 0.5 秒内将 alpha 更改为 0.5
  4. 此时,动画已经结束。所以 v View 恢复到状态 1 并重复然后动画。

状态 4 是完整 alpha 闪烁的地方,因为 v View 从 0.51.00.0 秒内。然而,计算机无法在 0.0 秒内完成任何事情(由于复杂的物理学实际上不可能),因此结果是在计算机尝试时瞬间闪现完整的 alpha尽可能接近 0.0 秒。

要避免这种情况,您可以将原始 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

选项 2:

//Import Statements
//Configuration and Initialization of v view
v.alpha = 0.0 //<-- Make sure to set the original alpha to 0.0

let duration: NSTimeInterval = 1.8
let third: NSTimeInterval = 1/3

UIView.animateKeyframesWithDuration(duration, delay: 0, options: .Repeat, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: third, animations: {
v.alpha = 0.0
})
UIView.addKeyframeWithRelativeStartTime(third, relativeDuration: third, animations: {
v.alpha = 0.5
})
//Key Point Below. Added Another Frame!
UIView.addKeyframeWithRelativeStartTime(third*2, relativeDuration: third, animations: {
v.alpha = 0.0
})
}, completion: nil)

XCPlaygroundPage.currentPage.liveView = v

关于swift - UIView.animateKeyFramesWithDuration 动画不流畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38022455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com