CABasicAnimation关键帧动画

2015-12-28  本文已影响457人  kysonyangs

所谓关键帧动画,就是将Layer的属性作为KeyPath来注册,指定动画的起始帧和结束帧,然后自动计算和实现中间的过度的一种动画方式。

CABasicAnimation 基本动画

基本使用方法:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 1;
animation.fromValue = @1;
animation.toValue = @0.f;
// 设置完动画之后一定要添加到你想要执行的Layer上,要不,动画无效
[layer addAnimation:animation forKey:@"myopacity"];

属性说明:

animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;

最后,动画执行完成后要记得将layer上的动画删除。

[self.myview.layer removeAllAnimations];

举个🌰: 我们弄个改变Layer透明度的动画,代码见下:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = 1;
animation.repeatCount = HUGE_VALL;
animation.autoreverses = YES;
animation.fromValue = @1;
animation.toValue = @0.f;
[layer addAnimation:animation forKey:@"myopacity"];

效果如图:

1.gif

再来一个它常用的组合类型:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    CGSize size = self.bounds.size;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(size.width, 0)];
    [path addLineToPoint:CGPointMake(size.width, size.height)];
    [path addLineToPoint:CGPointMake(0, size.height)];
    [path closePath];
    
    self.mylayer = [CAShapeLayer layer];
    self.mylayer.frame = self.bounds;
    self.mylayer.lineWidth = 5;
    self.mylayer.strokeColor = [UIColor redColor].CGColor;
    self.mylayer.path = path.CGPath;
    [self.layer addSublayer:self.mylayer];
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 1.0;
    pathAnimation.repeatCount = HUGE_VALF;
    pathAnimation.autoreverses = YES;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.f];
    [self.mylayer addAnimation:pathAnimation forKey:nil];
}

效果图:

2.gif
上一篇 下一篇

猜你喜欢

热点阅读