1.創建復制圖層
CAReplicatorLayer *replicator = [CAReplicatorLayer layer];
replicator.frame = CGRectMake(50, 50, 200, 200);
replicator.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:replicator];
2.創建一個矩形圖層,設置縮放動畫。
CALayer *indicator = [CALayer layer];
indicator.transform = CATransform3DMakeScale(0, 0, 0);
indicator.position = CGPointMake(100, 20);
indicator.bounds = CGRectMake(0, 0, 10, 10);
indicator.backgroundColor = [UIColor greenColor].CGColor;
[replicator addSublayer:indicator];
CGFloat durtion = 1;
CABasicAnimation *anim = [CABasicAnimation animation];
anim.keyPath = @"transform.scale";
anim.fromValue = @1;
anim.toValue = @0.1;
anim.repeatCount = MAXFLOAT;
anim.duration = durtion;
[indicator addAnimation:anim forKey:nil];
3.復制矩形圖層,並且設置每個復制層的角度形變
int count = 10;
// 設置子層次數
replicator.instanceCount = count;
// 設置子層形變角度
CGFloat angle = M_PI * 2 / count;
replicator.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 1);
4.設置復制動畫延長時間(需要保證第一個執行完畢之後,繞一圈剛好又是從第一個執行,因此需要把動畫時長平均分給每個子層)
公式:延長時間 = 動畫時長 / 子層總數
假設有兩個圖層,動畫時間為1秒,延長時間就為0.5秒。當第一個動畫執行到一半的時候(0.5),第二個開始執行。第二個執行完
// 設置子層動畫延長時間
replicator.instanceDelay = durtion / count;
#import "ViewController.h"
#define Count 20.0
#define DurationTime 1.0
@interface ViewController ()
@property (nonatomic,strong) CAReplicatorLayer *replicator;
@property (nonatomic,strong) CALayer *indicator;
@property (nonatomic,strong) CABasicAnimation *anim;
@end
@implementation ViewController
//懶加載,復制層
- (CAReplicatorLayer *)replicator
{
if (_replicator == nil) {
_replicator = [CAReplicatorLayer layer];
_replicator.frame = CGRectMake(50, 50, 200, 200);
_replicator.backgroundColor = [UIColor clearColor].CGColor;
// 設置子層次數
_replicator.instanceCount = Count;
// 設置子層動畫延長時間
_replicator.instanceDelay = DurationTime / Count;
// 設置子層形變角度
CGFloat angle = M_PI * 2 / Count;
_replicator.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 1);
}
return _replicator;
}
//普通層
- (CALayer *)indicator
{
if (_indicator == nil) {
_indicator = [CALayer layer];
_indicator.transform = CATransform3DMakeScale(0, 0, 0);
_indicator.position = CGPointMake(100, 20);
_indicator.bounds = CGRectMake(0, 0, 10, 10);
_indicator.cornerRadius = 5;
_indicator.backgroundColor = [UIColor greenColor].CGColor;
}
return _indicator;
}
//動畫
- (CABasicAnimation *)anim
{
if (_anim == nil) {
_anim = [CABasicAnimation animation];
_anim.keyPath = @"transform.scale";
_anim.fromValue = @1;
_anim.toValue = @0.1;
_anim.repeatCount = MAXFLOAT;
_anim.duration = DurationTime;
}
return _anim;
}
- (void)viewDidLoad {
[super viewDidLoad];
//添加復制層
[self.view.layer addSublayer:self.replicator];
//添加層
[self.replicator addSublayer:self.indicator];
//添加動畫
[self.indicator addAnimation:self.anim forKey:nil];
}
@end