iOS動畫之活動指標
1.結果展示
2.實現思路
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;
3.完整代碼
#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