iOS中关于Animation的一些小动画(钟摆,抖动,摇晃)

iOS 301 2018-09-17 16:17

今天给大家带来的是关于Animation中一些动画效果,先上图吧!

iOS中关于Animation的一些小动画(钟摆,抖动,摇晃)-JEESNS

使用多张图片,设置图片位置并对每一张图片添加不同的动画效果,进而实现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];
}

好了,以上就是第一个动画的分析,至于其他动画的效果我就不多说了,下面是动画的代码,需要的可以去研究下。

https://github.com/xiaojin1123/AnimationDemo.git

文章评论