问题描述
我创建了一个 CAShapeLayer
作为一个圆圈,并添加了一些动画,在图像加载时填充它,直到圆圈完全填充并显示图像。
我使用 Alamofire 的 .fractionCompleted
作为我的 shapeLayer.strokeEnd
属性的值(它定义了圆圈填满的速度)。但它有一个奇怪的行为;它完全加载,然后向后移动,然后完全填满,然后再次返回,依此类推。
以下是说明情况的 GIF:Click to see
API 调用如下:
class Service {
var delegate: ServiceDelegate?
let baseUrl = "https://picsum.photos/id/0/5616/3744"
typealias ImageCallback = (UIImage) -> Void
func fetchImage(handler: @escaping ImageCallback) {
AF.request(baseUrl).validate().downloadProgress { progress in
let percentage = CGFloat(progress.fractionCompleted)
self.delegate?.sendProgress(progress: percentage)
}.response { (response) in
do {
guard let data = response.data,let image = UIImage(data: data)
else { return }
handler(image)
} catch {
print("DEBUG ERROR: \(error)")
}
}.resume()
}
}
以下是在 VC 上实现的 ServiceDelegate 函数:
extension ViewController: ServiceDelegate {
func sendProgress(progress: CGFloat) {
dispatchQueue.main.async {
self.animateCircle(strokeEnd: progress)
}
print(progress)
}
}
基本动画代码:
func animateCircle(strokeEnd: CGFloat) {
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.tovalue = 1
basicAnimation.duration = 2
basicAnimation.fillMode = .forwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.strokeEnd = strokeEnd
shapeLayer.add(basicAnimation,forKey: "randomKey")
}
如果您需要另一块代码,请告诉我。
解决方法
没关系,我解决了。我的问题是我仍在使用 animateCircle() 函数,即使 shapeLayer.strokeEnd 被认为可以完成完全相同的工作。当我评论该功能时,它运行良好。