Core Animation一些Demo总结 (动态切换图片、大转盘、图片折叠、进

2019-12-10 19:03:23王旭

4、旋转进度条

圆圈旋转一般都是放在HUD上吧。记得以前我也做过一个类似的功能,那时候还没现在这样的知识储备,只能是用CAKeyframeAnimation做,让美工做出了一根顶部是一个小白点,除此之外,很长的那部分是为clearColor的小矩形,然后我设置它的anchorPoint,给 CAKeyframeAnimation添加一个圆形的path,然后围绕这个path旋转,做是勉强做出来,但是很不好看吧。

现在可以有更好的选择了,CAReplicatorLayer(复制图层)。我们可以在复制图层里面添加一个instance图层,如果设置了复制图层的instanceCount,假如让instanceCount == 5, 那么复制图层会自动帮我们复制5个跟instance图层一样的图层(事实上,我们可以在一开始就给instance图层设置动画,那么在复制的时候,一样会把动画也复制过来),除此之外,还可以设置复制图层里面的instance图层的transfrom,从而实现一定的布局。复制图层里面还有一个instanceDelay,它表示延迟多少时间开始动画等等。

这个Demo就是用了上面所说的实现的,代码:

#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *containView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self setupReplicatorLayerAndAnimation];
}
- (void)setupReplicatorLayerAndAnimation
{
CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
replicatorLayer.frame = self.containView.layer.bounds;
[self.containView.layer addSublayer:replicatorLayer];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(self.containView.frame.size.width * 0.5, 20, 16, 16);
layer.backgroundColor = [UIColor redColor].CGColor;
layer.cornerRadius = layer.frame.size.width / 2;
//这一句可以将初始过程移除掉
layer.transform = CATransform3DMakeScale(0, 0, 0);
[replicatorLayer addSublayer:layer];
replicatorLayer.instanceCount = 22;
CABasicAnimation *basicAn = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
basicAn.fromValue = @1;
basicAn.toValue = @0;
basicAn.duration = 1;
basicAn.repeatCount = MAXFLOAT;
[layer addAnimation:basicAn forKey:nil];
replicatorLayer.instanceDelay = basicAn.duration / (double)replicatorLayer.instanceCount;
replicatorLayer.instanceTransform = CATransform3DMakeRotation(2 * M_PI / replicatorLayer.instanceCount, 0, 0, 1);
}
@end