iOS中關於Animation的一些小動畫(鐘擺,抖動,搖晃)
今天給大家帶來的是關於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]; }
好了,以上就是第一個動畫的分析,至於其他動畫的效果我就不多說了,下面是動畫的程式碼,需要的可以去研究下。
ofollow,noindex">https://github.com/xiaojin1123/AnimationDemo.git