CAReplicatorLayer使用

之前埋了个坑,要介绍一下这个CAReplicatorLayer的,结果一直也没写,今天想起来还是简单写一下吧。

直接上代码:

override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        let subView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        subView.backgroundColor = UIColor.lightGray
        view.addSubview(subView)
        
        let animatedLayer = CALayer()
        animatedLayer.frame = CGRect(x: 0, y: 45, width: 10, height: 10)
        animatedLayer.cornerRadius = 5
        
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.fromValue = NSNumber(value: 1)
        animation.toValue = NSNumber(value: 0.5)
        animation.duration = 1.9
        animation.autoreverses = false
        animation.repeatCount = Float.greatestFiniteMagnitude
        
        animatedLayer.backgroundColor = UIColor.red.cgColor
        animatedLayer.add(animation, forKey: "scale")
        
        let replicatorLayer = CAReplicatorLayer()
        replicatorLayer.frame = subView.bounds
        replicatorLayer.addSublayer(animatedLayer)
        replicatorLayer.instanceCount = 20
        replicatorLayer.instanceDelay = 0.1
        replicatorLayer.instanceTransform = CATransform3DMakeRotation(CGFloat.pi*2/20, 0, 0, 1)
        
        subView.layer.addSublayer(replicatorLayer)
    }

简单说一下,就是只要创建一个** CAReplicatorLayer**,然后在这个layer上添加子layer,就可以根据需要复制出相应的layer(复制的是子layer),如果子layer有动画,它复制出的也会执行动画,这就很有灵性了,看一下每个属性都是做什么的:

instanceCount:需要复制的数量
instanceDelay:复制出来的layer执行动画跟上一个执行动画的延迟
instanceTransform:复制出的layer的排列规则


CAReplicatorLayer使用_第1张图片
indicator.gif

你可能感兴趣的:(CAReplicatorLayer使用)