首页 > 代码库 > ios开发核心动画五:图标抖动效果--CAKeyframeAnimation

ios开发核心动画五:图标抖动效果--CAKeyframeAnimation

#import "ViewController.h"#define angle2Rad(angle) ((angle) / 180.0 * M_PI)@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageV;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {                /**     1:UIBezierPath:是绘制路径的类,moveToPoint设置起点,addLineToPoint,从起点绘制一条路径,在执行addLineToPoint,则从终点作为起点,在绘制一条路径,要转为CGPath     *     */    //1.创建动画对象    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];        anim.duration = 2;        UIBezierPath *path = [UIBezierPath bezierPath];    [path moveToPoint:CGPointMake(50, 50)];    [path addLineToPoint:CGPointMake(300, 50)];    [path addLineToPoint:CGPointMake(300, 400)];        anim.keyPath =  @"position";    anim.path = path.CGPath;        [self.imageV.layer addAnimation:anim forKey:nil];}//图标抖动- (void)icon {        //1.创建动画对象    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];        //2.设置属性值    /**1:keyPath为layear下的属性的keypath路径 2:values是一个数组,在values数组里定义的对象都会产生动画效果,让图标先向左移动-3弧度,再动画回来移动到3弧度,在动画移动到-3,无限重复       2:也可以设置动画的翻转效果:anim.values = @[@(angle2Rad(-3)),@(angle2Rad(3))],anim.autoreverses,这样执行完values里的动画到3弧度后,还会动画回来继续重复,否则不会产生动画       3:再把动画添加到layear层上,核心动画都是作用砸layear层上     *     */    anim.keyPath = @"transform.rotation";    anim.values = @[@(angle2Rad(-3)),@(angle2Rad(3)),@(angle2Rad(-3))];        //3.设置动画执行次数    anim.repeatCount =  MAXFLOAT;        anim.duration = 0.5;        //anim.autoreverses = YES;            [self.imageV.layer addAnimation:anim forKey:nil];        }@end

1.帧动画介绍:

CAKeyframeAnimation它可以在多个值之间进行动画.

设置多值之间的属性为:

后面是一个数组,就是要设置的多个值.

anim.values = @[];

 

它还可以根据一个路径做动画.

anim.path = 自己创建的路径.

 

2.图片抖动思路:

其实就是做一个左右旋转的动画.先让它往左边旋转-5,再往右边旋转5度,再从5度旋转到-5度.

就会有左右摇摆的效果了.

 

具体实现代码

创建帧动画

CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];

设置动画属性为旋转

anim.keyPath = @"transform.rotation";

设置属性值为多个属性

anim.values = @[@(angle2radio(-5)),@(angle2radio(5)),@(angle2radio(-5))];

设置动画执行次数

anim.repeatCount = MAXFLOAT;

添加动画

[_imageView.layer addAnimation:anim forKey:nil];

 

3.根据圆形的路径做移动的效果.

创建路径

UIBezierPath *path = [UIBezierPath 

  bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)];

       [path addLineToPoint:CGPointMake(200, 500)];

       

       把路径设为动画的属性

       anim.path = path.CGPath;

 

技术分享

 

ios开发核心动画五:图标抖动效果--CAKeyframeAnimation