iOS自定义动画-仿支付宝记账本
CALayer大部分属性都可以添加CAAnimation动画,动画添加到layer上之后就会自动开始执行,但这仅限于CALayer及其子类已有的属性,如果是自己添加的属性,是不会自动产生动画的,如果需要动画效果,就需要自定义动画了。
如何创建自定义动画?
大体来说有两种方法,一种是使用系统的绘制方法画出动画,一种是利用定时器自己绘制动画。
方法一
1、创建自定义Layer类继承自CAShapeLayer
2、给Layer添加需要执行动画的属性,在.m文件中使用@dynamic声明动画属性
3、重写几个系统方法:
// 告诉CALayer自定义属性需要进行重绘
+ (BOOL)needsDisplayForKey:(NSString *)key {
if ([key isEqualToString:@"startAngle"]||[key isEqualToString:@"endAngle"]) {
return YES;
}
return [super needsDisplayForKey:key];
}
// 如果自定义属性值改变,就生成动画,系统会自动调用display方法重绘
- (id<CAAction>)actionForKey:(NSString *)event {
if ([event isEqualToString:@"startAngle"])
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:event];
anim.duration = 1;
anim.fromValue = @([self.presentationLayer startAngle]);
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
return anim;
} else if ([event isEqualToString:@"endAngle"]) {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:event];
anim.duration = 1;
anim.fromValue = @([self.presentationLayer endAngle]);
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
return anim;
}
return [super actionForKey:event];
}
重写上面两个方法之后,在外部修改动画属性时就会触发界面重绘。系统会优先调用-display
方法进行重绘,如果没有重写这个方法,系统会调用-drawInContext:
进行重绘。要注意:
不在-drawInContext中绘图的时候,要在绘图代码前后加上:
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
在-drawInContext中绘制的时候不需要写。
绘制代码:
- (void)drawInContext:(CGContextRef)ctx {
CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
CGFloat presentStartAngle = [[self.presentationLayer valueForKey:@"startAngle"] doubleValue];
CGFloat presentEndAngle = [[self.presentationLayer valueForKey:@"endAngle"] doubleValue];
CGContextSetLineWidth(ctx, 40);
CGContextSetStrokeColorWithColor(ctx, [UIColor purpleColor].CGColor);
CGContextAddArc(ctx, center.x, center.y, 100, presentStartAngle, presentEndAngle, 0);
CGContextStrokePath(ctx);
}
- (void)display {
CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
CGFloat presentStartAngle = [[self.presentationLayer valueForKey:@"startAngle"] doubleValue];
CGFloat presentEndAngle = [[self.presentationLayer valueForKey:@"endAngle"] doubleValue];
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 40);
[self.color setStroke];
CGContextAddArc(ctx, center.x, center.y, 100, presentStartAngle, presentEndAngle, 0);
CGContextStrokePath(ctx);
self.contents = (id)UIGraphicsGetImageFromCurrentImageContext().CGImage;
UIGraphicsEndImageContext();
}
创建这个Layer对象的时候,需要给它设置frame,如果不设置frame,会出现绘制失败。所以最好用-initWithFrame:
方法进行创建。
方法二
理论上讲重绘方法每秒会被调用60次,但真机实测发现只有50多次,并且调用次数会随着重绘代码的增多而减少,这会造成动画帧数下降,使动画看起来不够流畅。
第二种方法是创建定时器,每秒触发60次,每次触发都进行重绘,步骤:
1、创建Layer类继承自CAShapeLayer,重写-initWithLayer:
方法
2、创建UIView类用来放置Layer,在view被添加到父视图之后给它上面的Layer创建动画
3、实现动画代理方法,动画开始时开启定时器,定时触发重绘
4、动画属性的值会随动画的执行不断变化,定时器触发时获取当前动画值,画出当前的位置
重写-initWithLayer:
:
- (instancetype)initWithLayer:(id)layer {
if (self = [super initWithLayer:layer]) {
if ([layer isKindOfClass:[CircleLayer class]]) {
self.startAngle = [(CircleLayer *)layer startAngle];
self.endAngle = [(CircleLayer *)layer endAngle];
}
}
return self;
}
CAAnimation生成关键帧是通过拷贝CALayer进行的,在拷贝时,只能拷贝原有的(系统的,非自定义的)属性,不能拷贝自定义的属性或持有的对象等等,因此需要重载initWithLayer来手动拷贝我们需要拷贝的东西。
创建动画:
- (void)createAnimationWithKeyPath:(NSString *)key fromValue:(NSNumber *)from toValue:(NSNumber *)to func:(NSString *)func layer:(CALayer *)layer {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:key];
NSNumber *currentAngle = [layer.presentationLayer valueForKey:key];
if (!currentAngle) {
currentAngle = from;
}
anim.fromValue = currentAngle;
anim.toValue = to;
anim.delegate = self;
anim.timingFunction = [CAMediaTimingFunction functionWithName:func];
[layer addAnimation:anim forKey:key];
// 设置结束值,这样动画结束之后就会停留在结束位置,而不会返回初始位置,一定要在添加动画之后设置
[layer setValue:to forKey:key];
}
给动画设置初始值和结束值,设置好动画执行方式,它就会在“暗地里”执行,执行期间可以通过layer.presentationLayer
获取当前动画执行到的位置,获取之后就可以绘制layer了。这样每秒绘制60次就形成了流畅的动画效果。
支付宝的记账本里有一个非常酷炫的自定义控件,现在就模仿一下它的动画效果:
仿支付宝记账本.gif代码如下:
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_animations = [[NSMutableArray alloc] init];
_pieCenter = CGPointMake(frame.size.width/2, frame.size.height/2);
_animationDuration = 3;
_startPieAngle = 0;
_pieLineWidth = 40;
_pieRadius = MIN(frame.size.width/2 - _pieLineWidth, frame.size.width/2 - _pieLineWidth);
_selectedIndex = -1;
_selectedOffsetRadius = 7.0;
}
return self;
}
- (void)reloadData {
[CATransaction begin];
[CATransaction setAnimationDuration:_animationDuration];
CGFloat p = 2 * M_PI;
NSArray *end = @[@(p/5),@(p/4),@(p/3),@(p/2),@(p/1)];
NSArray *start = @[@(0),@(p/5),@(p/4),@(p/3),@(p/2)];
for (int i = 0; i < 5; i ++) {
CircleLayer *layer = [CircleLayer layer];
[self.layer addSublayer:layer];
CGFloat startAngle = [start[i] doubleValue];
CGFloat endAngle = [end[i] doubleValue];
layer.startAngle = startAngle;
layer.endAngle = endAngle;
layer.lineWidth = 30;
layer.fillColor = [UIColor clearColor].CGColor;
layer.strokeColor = [UIColor colorWithHue:((i/8)%20)/20.0+0.02 saturation:(i%8+3)/10.0 brightness:91/100.0 alpha:1].CGColor;
[self createAnimationWithKeyPath:@"startAngle" fromValue:@0 toValue:@(startAngle) layer:layer];
[self createAnimationWithKeyPath:@"endAngle" fromValue:@0 toValue:@(endAngle) layer:layer];
}
[CATransaction commit];
}
- (void)createAnimationWithKeyPath:(NSString *)key fromValue:(NSNumber *)from toValue:(NSNumber *)to layer:(CALayer *)layer {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:key];
NSNumber *currentAngle = [layer.presentationLayer valueForKey:key];
if (!currentAngle) {
currentAngle = from;
}
anim.fromValue = currentAngle;
anim.toValue = to;
anim.delegate = self;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[layer addAnimation:anim forKey:key];
[layer setValue:to forKey:key];
}
- (void)animationDidStart:(CAAnimation *)anim {
if (!_animationTimer) {
static float timeInterval = 1.0/60.0;
_animationTimer= [NSTimer timerWithTimeInterval:timeInterval target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_animationTimer forMode:NSRunLoopCommonModes];
}
[_animations addObject:anim];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
[_animations removeObject:anim];
if (_animations.count == 0) {
[_animationTimer invalidate];
_animationTimer = nil;
}
}
- (void)timerFired {
NSArray *sliceLayerArray = self.layer.sublayers;
[sliceLayerArray enumerateObjectsUsingBlock:^(CircleLayer *layer, NSUInteger idx, BOOL *stop) {
CGFloat currentStartAngle = [[layer.presentationLayer valueForKey:@"startAngle"] doubleValue];
CGFloat currentEndAngle = [[layer.presentationLayer valueForKey:@"endAngle"] doubleValue];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:_pieCenter radius:_pieRadius startAngle:currentStartAngle endAngle:currentEndAngle clockwise:1];
layer.path = path.CGPath;
}];
}
添加到ViewController上之后,调用reloadData
就会开始动画。
仿写的支付宝记账本控件效果如下:
6.gif完整demo请参考我的GitHub。