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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM