#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
本文介绍了一个iOS应用中的动画实现案例,包括关键帧动画的创建及触发方式。通过触摸事件启动动画,利用Core Animation实现视图沿特定路径移动的效果,并展示了如何为视图添加摇晃动画。
3万+

被折叠的 条评论
为什么被折叠?



