如何为UIView实现CAGradientLayer无限定向渐变动画及图层隐藏问题
问题1:无限滚动渐变动画实现
原有代码存在几个明显错误:
colors数组只有2个元素,但你给locations赋值了3个元素,数量不匹配,系统会忽略异常的配置项- 动画的起始和结束状态没有保持视觉一致,循环时会出现跳变,无法做到无缝衔接
- 动画逻辑不符合「20%纯白色块+蓝色背景滚动」的需求
实现无缝无限滚动的核心是让动画结束状态和起始状态视觉完全一致,推荐用「加宽渐变层+位移动画」的方案,逻辑更简单,也更容易控制白色块占比:
let loadingView = UIView(frame: frame) view.addSubview(loadingView) // 先把loadingView加到父视图上 let gradient = CAGradientLayer() // 渐变层宽度设为loadingView的2倍,保证滚动时无缝衔接 gradient.frame = CGRect(x: -loadingView.bounds.width, y: 0, width: loadingView.bounds.width * 2, height: loadingView.bounds.height) // 颜色配置:蓝色背景 + 中间20%的纯白色块,前后补蓝色保证滚动无缝 gradient.colors = [ UIColor.blue.cgColor, UIColor.blue.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.blue.cgColor, UIColor.blue.cgColor ] // 水平渐变配置 gradient.startPoint = CGPoint(x: 0, y: 0.5) gradient.endPoint = CGPoint(x: 1, y: 0.5) // 配置白色块占比为20%:第2和第3个颜色点之间的间隔是0.2,对应20%宽度 gradient.locations = [0, 0.4, 0.4, 0.6, 0.6, 1] // 把渐变层加到loadingView的layer上 loadingView.layer.addSublayer(gradient) // 位移动画:让渐变层从左向右移动,结束状态和起始状态视觉一致 let animation = CABasicAnimation(keyPath: "position.x") animation.fromValue = 0 animation.toValue = loadingView.bounds.width animation.duration = 1.5 animation.repeatCount = .infinity animation.isRemovedOnCompletion = false gradient.add(animation, forKey: "gradientScrollAnimation")
- 注意:如果你的loadingView会动态调整尺寸(比如屏幕旋转、自适应布局),需要在
layoutSubviews或者viewDidLayoutSubviews中同步更新gradient的frame,避免渐变变形。
问题2:隐藏父视图时渐变层不消失的解决方案
你的代码里把CAGradientLayer直接添加到了当前控制器的view.layer上,和你创建的loadingView是同级层级关系,所以修改loadingView.isHidden当然不会影响渐变层的显隐。
按照上面给出的代码,把渐变层加到loadingView.layer上之后,修改loadingView.isHidden就可以同时控制渐变层的显隐了。
内容的提问来源于stack exchange,提问作者Another Dude
相关产品推荐
相关产品推荐

