ShapeLayer.strokeEnd 在 Swift

问题描述

我创建了一个 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")
}

如果您需要另一块代码,请告诉我。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)