UIView.animateKeyFramesWithDuration 动画不流畅

UIView.animateKeyFramesWithDuration not animating smoothly

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

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,然后重复动画。为了弥补这一点并获得你想要的效果,你可以考虑在运行 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 视图恢复到状态 1 然后重复动画。

状态 4 是完整 alpha 闪烁的地方,因为 v 视图正在从 0.5 变为 1.00.0 秒内。但是,计算机无法在 0.0 秒内发生任何事情(由于复杂的物理学实际上不可能发生)所以结果是在计算机试图尽可能接近 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