CAReplicatorLayer复制Layer和动画, 实现神奇的效果

时间:2023-12-05 15:04:32

今天我们看下CAReplicatorLayer, 官方的解释是一个高效处理复制图层的中间层。他能复制图层的所有属性包括动画

一样我们先看下头文件

@interface CAReplicatorLayer : CALayer

@property NSInteger instanceCount;
//复制的个数
@property BOOL preservesDepth;
//这是一个bool值,默认为No,如果设为Yes,将会具有3维透视效果
@property CFTimeInterval instanceDelay;
//复制后的layer相比原来的距离
@property CATransform3D instanceTransform;
//复制layer的坐标系/方向偏转
@property(nullable) CGColorRef instanceColor; @property float instanceRedOffset;
@property float instanceGreenOffset;
@property float instanceBlueOffset;
@property float instanceAlphaOffset; @end

我们可以通过CAReplicatorLayer实现很炫的动画, 比如这个

CAReplicatorLayer复制Layer和动画, 实现神奇的效果

上代码:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //创建一个红色的圆形CALayer
CALayer * layer = [CALayer layer];
layer.bounds = CGRectMake(, , , );
layer.position = CGPointMake(self.view.center.x - , self.view.center.y - );
layer.backgroundColor = [UIColor redColor].CGColor;
layer.cornerRadius = ;
[self.view.layer addSublayer:layer]; //创建一个透明度动画
CABasicAnimation * animation1 = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation1.fromValue = @();
animation1.toValue = @();
animation1.duration = 1.5;
animation1.autoreverses = YES; //创建一个缩放动画
CABasicAnimation * animation2 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
animation2.toValue = @(1.5);
animation2.fromValue = @(0.5);
animation2.duration = 1.5;
animation2.autoreverses = YES; //创建一个动画组, 将之前创建的透明度动画和缩放动画加入到这个动画组中
CAAnimationGroup * ani = [CAAnimationGroup animation];
ani.animations = @[animation1,animation2];
ani.duration = 1.5;
ani.repeatCount = MAXFLOAT;
ani.autoreverses = YES; //将动画组添加到layer
[layer addAnimation:ani forKey:nil]; CAReplicatorLayer * rec = [CAReplicatorLayer layer];
rec.instanceCount = ;
rec.instanceDelay = 0.5;
rec.instanceTransform = CATransform3DMakeTranslation(, , );
[rec addSublayer:layer];
[self.view.layer addSublayer:rec]; CAReplicatorLayer * rec2 = [CAReplicatorLayer layer];
rec2.instanceCount = ;
rec2.instanceDelay = 0.5;
rec2.instanceTransform = CATransform3DMakeTranslation(, , );
[rec2 addSublayer:rec];
[self.view.layer addSublayer:rec2];
} @end

利用CAReplicatorLayer可以实现很多神奇的效果, 大家可以在发挥下脑洞