参考网址:
http://www.jianshu.com/p/b05986ded337
http://www.jianshu.com/p/69f9b00dabdc
#import "ViewController.h" #define K_SCREEN_W [UIScreen mainScreen].bounds.size.width #define K_SCREEN_H [UIScreen mainScreen].bounds.size.height @interface ViewController () @property (weak, nonatomic) IBOutlet UIView *greenView; @property (nonatomic, weak) CALayer *redLayer; - (IBAction)SegueDetailClick:(UIButton *)sender; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; /** * 概念:关键帧动画-CAKeyframeAnimation 与基础动画的区别: 基础动画只能是某个属性的初始值到另一个值产生动画效果; 关键帧动画支持多个值(values)或者一个路径(path) */ // 1. 添加redLayer图层 到view.layer上 [self addRedLayer]; } - (void)addRedLayer{ CALayer *layer = [CALayer layer]; _redLayer = layer; layer.backgroundColor = [UIColor redColor].CGColor; CGFloat la_w = 100; CGFloat la_h = la_w; CGFloat la_x = (K_SCREEN_W - la_w)/2; CGFloat la_y = (K_SCREEN_H - la_h)/2; layer.frame = CGRectMake(la_x, la_y, la_w, la_h); [self.view.layer addSublayer:_redLayer]; } - (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{ /** 2. 绿色的view,椭圆路径位移 */ [self positionChange]; /** _redLayer 抖动 动画 */ [self anim]; } - (void)positionChange{ CAKeyframeAnimation *anim = [CAKeyframeAnimation animation]; anim.keyPath = @"position"; anim.duration = 1; anim.repeatCount = MAXFLOAT; // 取消反弹 // 告诉在动画结束的时候不要移除 anim.removedOnCompletion = NO; // 始终保持最新的效果 anim.fillMode = kCAFillModeForwards; CGFloat pa_w = 250; CGFloat pa_h = pa_w; CGFloat padding = 60; CGFloat pa_x = padding; CGFloat pa_y = (K_SCREEN_H - pa_w)/2; // Oval 椭圆 路径轨迹 anim.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(pa_x, pa_y, pa_w, pa_h)].CGPath; // 将动画对象添加到 绿色视图的layer上去 [_greenView.layer addAnimation:anim forKey:nil]; } /** * _redLayer 抖动动画 */ - (void)anim{ CAKeyframeAnimation *anim = [CAKeyframeAnimation animation]; anim.duration = 0.3; anim.keyPath = @"transform"; NSValue *value = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((-15) / 180.0 * M_PI, 0, 0, 1)]; NSValue *value1 = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((15) / 180.0 * M_PI, 0, 0, 1)]; NSValue *value2 = [NSValue valueWithCATransform3D:CATransform3DMakeRotation((-15) / 180.0 * M_PI, 0, 0, 1)]; anim.values = @[value,value1,value2]; anim.repeatCount = MAXFLOAT; [_redLayer addAnimation:anim forKey:nil]; } - (IBAction)SegueDetailClick:(UIButton *)sender { [self performSegueWithIdentifier:@"SegueDetail" sender:self]; } @end