iosswiftcashapelayercabasicanimationcagradientlayer

How to make iOS moving gradient border keep moving in one direction forever without resetting to original location?


My below code shows the issue:

import UIKit
import SnapKit

class ViewController: UIViewController {

    let animatedBorderView = AnimatedGradientBorderView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        animatedBorderView.layer.cornerRadius = 20
        animatedBorderView.clipsToBounds = true
        view.addSubview(animatedBorderView)
        animatedBorderView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(400)
        }
    }
}

class AnimatedGradientBorderView: UIView {
    
    private let gradientLayer = CAGradientLayer()
    private let shapeLayer = CAShapeLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayers()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLayers()
    }
    
    private func setupLayers() {
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        gradientLayer.colors = [
            UIColor.systemRed.cgColor,
            UIColor.systemYellow.cgColor,
            UIColor.systemGreen.cgColor,
        ]
        gradientLayer.locations = [0, 0.3, 0.6, 1]
        layer.addSublayer(gradientLayer)
        
        shapeLayer.lineWidth = 5
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.black.cgColor
        gradientLayer.mask = shapeLayer
        
        startAnimating()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
        let path = UIBezierPath(roundedRect: bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2), cornerRadius: layer.cornerRadius)
        shapeLayer.path = path.cgPath
    }
    
    private func startAnimating() {
        let animation = CABasicAnimation(keyPath: "locations")
        animation.fromValue = [0, 0.2, 0.4, 0.6]
        animation.toValue = [0.4, 0.6, 0.8, 1]
        animation.duration = 2.0
        animation.repeatCount = .infinity
        animation.autoreverses = false
        gradientLayer.add(animation, forKey: "animateLocations")
    }
}

This produces the below animation:

enter image description here

Note that I have set autoreverses to false because I don't want it to reverse back when it's repeating to infinity. However, as a consequence of this, the problem is that after the duration, it restarts at the original location. This causes a sudden jump of the moving gradient border.

How can I make it just keep moving forever in one direction without it resetting?


Solution

  • To achieve a rotating border effect, I switched to a conic gradient (.conic), which naturally radiates colors around a center point. Instead of shifting the colors manually, the entire gradientLayer itself is rotated on the z axis. (Using Snake like gradient border animation in iOS as a reference)

    Try this:

    
    import UIKit
    import SnapKit
    
    class ViewController: UIViewController {
    
        let animatedBorderView = AnimatedGradientBorderView()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            animatedBorderView.colors = [.systemGreen,.systemYellow,.systemRed]
            animatedBorderView.layer.cornerRadius = 20
            animatedBorderView.clipsToBounds = true
            view.addSubview(animatedBorderView)
            animatedBorderView.snp.makeConstraints { make in
                make.horizontalEdges.equalTo(view.safeAreaLayoutGuide).inset(20)
                make.centerY.equalToSuperview()
                make.height.equalTo(50)
            }
        }
    }
    
    class AnimatedGradientBorderView: UIView {
    
        private let gradientLayer = CAGradientLayer()
        private let maskShape = CAShapeLayer()
        private let lineWidth = 3.0
        private var _colors = [UIColor]()
        var colors: [UIColor] {
            get {
                return _colors
            }
            set(newColors) {
                _colors = newColors
                var colorsToUse = _colors
                colorsToUse.append(contentsOf: colorsToUse.reversed().dropFirst())
                gradientLayer.colors = colorsToUse.map({$0.cgColor})
                let n = colorsToUse.count
                let locations = (0..<n).map { i in
                    NSNumber(value: Double(i) / Double(n - 1))
                }
                gradientLayer.locations = locations
            }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupLayers()
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setupLayers()
        }
    
        private func setupLayers() {
            gradientLayer.type = .conic
            gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
    
            layer.addSublayer(gradientLayer)
    
            maskShape.lineWidth = lineWidth
            maskShape.fillColor = nil
            maskShape.strokeColor = UIColor.white.cgColor
            layer.mask = maskShape
    
            let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotation.fromValue = 0
            rotation.toValue = CGFloat.pi * 2
            rotation.duration = 4.0
            rotation.repeatCount = .infinity
            gradientLayer.add(rotation, forKey: "rotateGradient")
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            
            maskShape.frame = bounds
            let insetRect = bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2)
            maskShape.path = UIBezierPath(
                roundedRect: insetRect,
                cornerRadius: layer.cornerRadius
            ).cgPath
    
            gradientLayer.bounds = CGRect(
                x: 0, y: 0,
                width: diagonalLength * 2,
                height: diagonalLength * 2
            )
            gradientLayer.position = CGPoint(x: bounds.midX, y: bounds.midY)
        }
    }
    
    extension UIView {
        var diagonalLength: CGFloat {
            return sqrt(bounds.width * bounds.width + bounds.height * bounds.height)
        }
    }