#import "CZViewController.h"
@interface CZViewController ()
@property ( nonatomic , strong ) UIView *myView;
@end
@implementation CZViewController
- ( UIView *)myView
{
if ( _myView == nil ) {
_myView = [[ UIView alloc ] initWithFrame : CGRectMake ( 110 , 100 , 100 , 100 )];
_myView . backgroundColor = [ UIColor redColor ];
[ self . view addSubview : _myView ];
}
return _myView ;
}
- ( void )viewDidLoad
{
[ super viewDidLoad ];
[ self myView ];
}
// 点击屏幕时调用
- ( void )touchesBegan:( NSSet *)touches withEvent:( UIEvent *)event
{
[ self positionAnim1 ];
}
#pragma mark - 关键帧动画
/** 摇晃动画 */
- ( void )shake
{
if ([ self . myView . layer animationForKey : @"shake" ]) return ;
CAKeyframeAnimation *anim = [ CAKeyframeAnimation animationWithKeyPath : @"transform.rotation" ];
anim. values = @[@( - M_PI / 36) , @( M_PI / 36) , @( - M_PI / 36)] ;
// anim.duration = 0.5f;
anim. repeatCount = MAXFLOAT ;
[ self . myView . layer addAnimation :anim forKey : @"shake" ];
}
// 图层在指定的路径上运动
- ( void )positionAnim1
{
CAKeyframeAnimation *anim = [ CAKeyframeAnimation animationWithKeyPath : @"position" ];
// 绘制圆形路径
anim. path = [ UIBezierPath bezierPathWithOvalInRect : CGRectMake ( 60 , 100 , 200 , 200 )]. CGPath ;
// 持续时间
anim. duration = 2.0f ;
[ self . myView . layer addAnimation :anim forKey : nil ];
}
// 在指定的几个点上运动
- ( void )positionAnim
{
CAKeyframeAnimation *anim = [ CAKeyframeAnimation animationWithKeyPath : @"position" ];
NSValue *p1 = [ NSValue valueWithCGPoint : CGPointMake ( 50 , 50 )];
NSValue *p2 = [ NSValue valueWithCGPoint : CGPointMake ( 50 , 300 )];
NSValue *p3 = [ NSValue valueWithCGPoint : CGPointMake ( 250 , 300 )];
NSValue *p4 = [ NSValue valueWithCGPoint : CGPointMake ( 250 , 50 )];
NSValue *p5 = [ NSValue valueWithCGPoint : CGPointMake ( 50 , 50 )];
anim. values = @[ p1, p2, p3, p4, p5 ] ;
// 图层会保持显示动画执行后的状态
// 设置保存动画的最新状态
anim. fillMode = kCAFillModeForwards ;
// 设置动画执行完毕之后不删除动画
anim. removedOnCompletion = NO ;
anim. duration = 2.0f ;
[ self . myView . layer addAnimation :anim forKey : nil ];
}
@end