有时候在开发中, 需要我们实现一个晃动动画,
达到一个提示的效果,如下图所示
思路, 我们要实现的本质上是一个旋转动画,然后
设置一个旋转角度,以底部中间为中心旋转,
左右各有一个旋转的角度,并且旋转角度逐渐变小,
动画速度逐渐变快,即时间间隔逐渐减小
代码
#define radian(angle) ((angle) / 180.0 * M_PI)
- (void)setUpUI
{
[self configCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight radius:6.5];
self.layer.backgroundColor = [UIColor redColor].CGColor;
self.textColor = [UIColor whiteColor];
self.font = [UIFont systemFontOfSize:9];
self.textAlignment = NSTextAlignmentCenter;
self.layer.anchorPoint = CGPointMake(0.5, 1);
self.layer.masksToBounds = YES;
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;
self.layer.position = CGPointMake(width / 2.f - 15, height/2.f + 5);
[self addMoveAnimation:self];
}
- (void)addMoveAnimation:(UIView *)view
{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
animation.delegate = self;
animation.keyPath = @"transform.rotation.z";
animation.values = @[@(radian(0)), @(radian(-15)), @(radian(0)), @(radian(15)),@(radian(0)),@(radian(-10)), @(radian(0)), @(radian(10)),@(radian(0)),@(radian(-7)), @(radian(0)), @(radian(7)),@(radian(0)),@(radian(-3)), @(radian(0)), @(radian(3)),@(radian(0)),@(radian(-1)), @(radian(0)), @(radian(1)),@(radian(0))];
animation.keyTimes = @[@0, @0.07, @0.14 , @0.21, @0.28, @0.35,@0.42, @0.49, @0.56, @0.63, @0.70, @0.75, @0.80, @0.85, @0.88,@0.91,@0.94, @0.96, @0.98,@0.99, @1];
animation.duration = 1;
// 动画的重复执行次数
animation. repeatCount = 1;
// 保持动画执行完毕后的状态
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeRemoved;
[view.layer addAnimation:animation forKey:@"shake_animation"];
}
#pragma mark - 动画代理
- (void)animationDidStop: (CAAnimation *)animation finished:(BOOL)flag
{
dispatshafter_ 2, NSOperationQueuePriorityHigh, ^{
[self addMoveAnimation:self];
});
}