iOS中关于Animation的一些小动画(钟摆,抖动,摇晃)
2017-05-23 本文已影响1258人
MR小锦
今天给大家带来的是关于Animation中一些动画效果,先上图吧!
AnimationDemo.gif一开始有人会认为这是用帧动画实现的效果。帧动画确实能够实现这种效果,但是,相对于这种比较耗内存的实现方法,我更加推荐下面的方法:
使用多张图片,图片位置的设置,对每一张图片添加不同的动画效果,进而实现demo中的效果。
一、分析(以第一个动画为例):项目中每一个小动画都是由三张图片组成的(除第三个动画以外);分为左上角是一张星星的图片,中间是一个标签图片,偏右下角的是另一张星星的图片。
以下是添加图片的代码:
CGRect frame = self.firstView.bounds;
UIImageView *imageView = [self createImageViewWithFrame:frame tag:kTAG_BASE_VALUE named:@"pic_ceshi2_biaoqian"];
imageView.layer.anchorPoint = CGPointMake(28.5/ 45.0, 16/ 45.0);
imageView.frame = frame;
[self.firstView addSubview:imageView];
imageView = [self createImageViewWithFrame:frame tag:kTAG_BASE_VALUE+1 named:@"pic_ceshi2_xingxing1"];
[self.firstView addSubview:imageView];
imageView = [self createImageViewWithFrame:frame tag:kTAG_BASE_VALUE+2 named:@"pic_ceshi2_xingxing2"];
[self.firstView addSubview:imageView];
二、如何添加动画:
1.计算出书签摆动的范围;
2.设置左上角星星的缩小数值;
3.设置偏右下角星星的放大数值;
- (void)startAnimationForFirstView{
id fromValue = [NSNumber numberWithFloat:-M_PI/ 10.0];
id toValue = [NSNumber numberWithFloat:M_PI/ 10.0];
UIImageView *imageView = [self.firstView viewWithTag:kTAG_BASE_VALUE];
[self animationWithView:imageView keyPath:@"transform.rotation.z" fromValue:fromValue toValue:toValue];
fromValue = @1;
toValue = @0.1;
imageView = [self.firstView viewWithTag:kTAG_BASE_VALUE + 1];
[self animationWithView:imageView keyPath:@"opacity" fromValue:fromValue toValue:toValue];
fromValue = @0.1;
toValue = @1;
imageView = [self.firstView viewWithTag:kTAG_BASE_VALUE + 2];
[self animationWithView:imageView keyPath:@"opacity" fromValue:fromValue toValue:toValue];
}
- (void)animationWithView:(UIView *)view keyPath:(NSString *)keyPath fromValue:(id)fromValue toValue:(id)toValue{
CAAnimation *animation = [self createAnimationWithKeyPath:keyPath fromValue:fromValue toValue:toValue];
[view.layer addAnimation:animation forKey:nil];
}
三、当程序退到后台的时候动画应该怎么处理?
可以在AppDelegate.m文件中添加上通知,然后在Controller中添加
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[NSNotificationCenter defaultCenter]postNotificationName:@"APPEnterForeground" object:nil];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//离屏后会remove animation,这里重新添加
[self restartAnimation];
//程序从后台进入激活状态需要重新添加Animation
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restartAnimation) name:@"APPEnterForeground" object:nil];
}
而且不要忘记要在Controller要viewWillDisappear的时候移除通知
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"APPEnterForeground" object:nil];
}