iOS Core Animation讲解---CABasicAn

2017-11-23  本文已影响14人  icoder

本文目录

_myView = [[UIView alloc] init];
_myView.layer.position = CGPointMake(100, 100);
_myView.layer.bounds = CGRectMake(0, 0, 100, 100);
_myView.backgroundColor = [UIColor blueColor];
[self.view addSubview:_myView];

一、平移动画

// 说明这个动画对象要对CALayer的position属性执行动画
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
// 动画持续1.5s
anim.duration = 1.5; 

// position属性值从(50, 80)渐变到(300, 350)
anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(50, 80)];
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(300, 350)];
// 设置动画的代理
anim.delegate = self;
// 保持动画执行后的状态
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeForwards;
// 添加动画对象到图层上
[_myView.layer addAnimation:anim forKey:@"translate"];

#pragma mark 动画开始
- (void)animationDidStart:(CAAnimation *)anim {
    NSLog(@"动画开始了");
}

#pragma mark 动画结束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    // 查看一下动画执行完毕后的position值
    NSString *string = NSStringFromCGPoint(_myView.layer.position);
    NSLog(@"动画结束了,position:%@", string);
}

实际上,动画执行完毕后,并没有真正改变CALayer的position属性的值
方法2

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
anim.duration = 1;
CATransform3D form = CATransform3DMakeTranslation(350, 350, 0);
anim.toValue = [NSValue valueWithCATransform3D:form];
[_myView.layer addAnimation:anim forKey:nil];

通过CALayer的transform属性实现平移动画,layer会从自己的初始位置平移到(350, 350)位置

二、缩放动画

实现缩放动画有好几种方法,这里列举2种。
1.方法1

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"bounds"];
anim.duration = 2;
anim.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 30, 30)];
[_myView.layer addAnimation:anim forKey:nil];

layer会从原来的尺寸(100x100)变为30x30
2.方法2

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
anim.duration = 1.5; // 动画持续1.5s
// CALayer的宽度从0.5倍变为2倍
// CALayer的高度从0.5倍变为1.5倍
anim.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1)];
anim.toValue  = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2, 1.5, 1)];
[_myView.layer addAnimation:anim forKey:nil];

三、旋转动画

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
anim.duration = 1.5;

// 绕着(0, 0, 1)这个向量轴顺时针旋转45°
anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_4, 0, 0, 1)];

[_myView.layer addAnimation:anim forKey:nil];
其实可以不用设置fromValue,这里只设置了toValue
四、其他

*CABasicAnimation
虽然能够做很多基本的动画效果,但是有个局限性,只能让CALayer的属性从某个值渐变到另一个值,仅仅是在2个值之间渐变

上一篇下一篇

猜你喜欢

热点阅读