iOS 為視圖添加抖動效果,ios視圖添加抖動
抖動效果在開發中比較少用到,不過有時使用了確有個很好的裝逼效果,用的時候就例如一些使用者錯誤操作之類的
效果如下,不過gif看到的效果沒實際的好看
上代碼
1 - (void)shakeAnimationForView:(UIView *) view 2 3 { 4 // 擷取到當前的View 5 6 CALayer *viewLayer = view.layer; 7 8 // 擷取當前View的位置 9 10 CGPoint position = viewLayer.position;11 12 // 移動的兩個終點位置13 14 CGPoint x = CGPointMake(position.x + 10, position.y);15 16 CGPoint y = CGPointMake(position.x - 10, position.y);17 18 // 設定動畫19 20 CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];21 22 // 設定運動形式23 24 [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];25 26 // 設定開始位置27 28 [animation setFromValue:[NSValue valueWithCGPoint:x]];29 30 // 設定結束位置31 32 [animation setToValue:[NSValue valueWithCGPoint:y]];33 34 // 設定自動反轉35 36 [animation setAutoreverses:YES];37 38 // 設定時間39 40 [animation setDuration:.06];41 42 // 設定次數43 44 [animation setRepeatCount:3];45 46 // 添加上動畫47 48 [viewLayer addAnimation:animation forKey:nil];49 50 51 52 }
只要在需要的地方傳進視圖就可以了
例如:
1 view1 = [[UIView alloc]initWithFrame:CGRectMake(50, 100, 50, 50)]; 2 view1.backgroundColor = [UIColor blueColor]; 3 view1.layer.cornerRadius = 25; 4 [self.view addSubview:view1]; 5 6 } 7 8 - (IBAction)beginView:(id)sender { 9 [self shakeAnimationForView:view1];10 }