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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,321评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 4,998评论 5 13
  • 转载:http://www.jianshu.com/p/32fcadd12108 每个UIView有一个伙伴称为l...
    F麦子阅读 5,952评论 0 13
  • 每个UIView有一个伙伴称为layer,一个CALayer。UIView实际上并没有把自己画到屏幕上;它绘制本身...
    shenzhenboy阅读 3,026评论 0 17
  • 上周与同学们的同题作文赛,没有来得及与大家分享,现在终于抽出一点儿时间了。 上课铃响了,首先主动分享习作的是肖立峰...
    石榴slr阅读 713评论 0 3