ios - 如何暂停 imageView 动画?
问题描述
我使用此代码为我的 imageView 创建旋转动画:
func rotate(imageView: UIImageView, aCircleTime: Double) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = -Double.pi * 2
rotationAnimation.duration = aCircleTime
rotationAnimation.repeatCount = .infinity
imageView.layer.add(rotationAnimation, forKey: nil)
}
但是如何暂停这个动画呢?
解决方案
可以暂停和恢复 CAAnimations,但它很繁琐而且有点混乱。看看 Github 上的这个项目:
https://github.com/DuncanMC/ClockWipeSwift.git
它在 CALayer 上使用了一个扩展:
// Credit to Rand, from Stack Overflow, for the basis of this extension
// see https://stackoverflow.com/a/59079995/205185
import UIKit
import CoreGraphics
import Foundation
extension CALayer
{
func isPaused() -> Bool {
return speed == 0
}
private func internalPause(_ pause: Bool) {
if pause {
let pausedTime = convertTime(CACurrentMediaTime(), from: nil)
speed = 0.0
timeOffset = pausedTime
} else {
let pausedTime = timeOffset
speed = 1.0
timeOffset = 0.0
beginTime = 0.0
let timeSincePause = convertTime(CACurrentMediaTime(), from: nil) - pausedTime
beginTime = timeSincePause
}
}
func pauseAnimation(_ pause: Bool) {
if pause != isPaused() {
internalPause(pause)
}
}
func pauseOrResumeAnimation() {
internalPause(isPaused())
}
}
如果使用 UIView 动画和 UIViewPropertyAnimator,暂停和恢复会容易得多。有很多教程解释了如何做到这一点。
你可以在 Github 上查看这个项目,它展示了如何使用UIViewPropertyAnimator
.
推荐阅读
- autosys - 如何将 autosys 作业开箱即用?
- c - 结构中动态数组的内存损坏?
- node.js - Redis 的 EVAL atomic wrt 是连接还是整个数据存储?
- regex - 匹配不在括号内的浮点数
- ssis - SSIS 数据源 - 忽略随机格式错误的行
- javascript - 在 React 中 useEffect 在值从其他组件更改后不会更新
- r - R:根据两个条件创建一个变量
- c# - c#错误cs0117'System.Diagnostics.Debug'不包含'Log'的定义
- python - 使用 docker 容器在生产中运行 celery 工人是否被认为是一种好习惯?
- json - 在从 HttpClient 请求获得的对象转换新类型之前,如何使用 rxjs 映射来改变对象中的数据?