有时候在开发中, 需要我们实现一个晃动动画,
达到一个提示的效果,如下图所示
思路, 我们要实现的本质上是一个旋转动画,然后
设置一个旋转角度,以底部中间为中心旋转,
左右各有一个旋转的角度,并且旋转角度逐渐变小,
动画速度逐渐变快,即时间间隔逐渐减小
代码
#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";
animation.values = @[@(radian(0)), @(radian(-25)), @(radian(0)), @(radian(25)),@(radian(0)),@(radian(-20)), @(radian(0)), @(radian(20)),@(radian(0)),@(radian(-10)), @(radian(0)), @(radian(10)),@(radian(0)),@(radian(-5)), @(radian(0)), @(radian(5)),@(radian(0)),];
animation.keyTimes = @[@0, @0.15, @0.3 , @0.45, @0.6, @0.7,@0.74, @0.78, @0.82, @0.86, @0.89, @0.92, @0.94, @0.96, @0.98,@0.99, @1];
animation.duration = 1.2;
// 动画的重复执行次数
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];
});
}