ios開發核心動畫五:圖標抖動效果--CAKeyframeAnimation


#import "ViewController.h"

#define angle2Rad(angle) ((angle) / 180.0 * M_PI)

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageV;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    
    
    /**
     1:UIBezierPath:是繪制路徑的類,moveToPoint設置起點,addLineToPoint,從起點繪制一條路徑,在執行addLineToPoint,則從終點作為起點,在繪制一條路徑,要轉為CGPath
     *
     */
    //1.創建動畫對象
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    
    anim.duration = 2;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(50, 50)];
    [path addLineToPoint:CGPointMake(300, 50)];
    [path addLineToPoint:CGPointMake(300, 400)];
    
    anim.keyPath =  @"position";
    anim.path = path.CGPath;
    
    [self.imageV.layer addAnimation:anim forKey:nil];

}



//圖標抖動
- (void)icon {
    
    //1.創建動畫對象
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    
    //2.設置屬性值
    /**1:keyPath為layear下的屬性的keypath路徑 2:values是一個數組,在values數組里定義的對象都會產生動畫效果,讓圖標先向左移動-3弧度,再動畫回來移動到3弧度,在動畫移動到-3,無限重復
       2:也可以設置動畫的翻轉效果:anim.values = @[@(angle2Rad(-3)),@(angle2Rad(3))],anim.autoreverses,這樣執行完values里的動畫到3弧度后,還會動畫回來繼續重復,否則不會產生動畫
       3:再把動畫添加到layear層上,核心動畫都是作用砸layear層上
     *
     */
    anim.keyPath = @"transform.rotation";
    anim.values = @[@(angle2Rad(-3)),@(angle2Rad(3)),@(angle2Rad(-3))];
    
    //3.設置動畫執行次數
    anim.repeatCount =  MAXFLOAT;
    
    anim.duration = 0.5;
    
    //anim.autoreverses = YES;
    
    
    [self.imageV.layer addAnimation:anim forKey:nil];
    
    
}
@end

1.幀動畫介紹:

CAKeyframeAnimation它可以在多個值之間進行動畫.

設置多值之間的屬性為:

后面是一個數組,就是要設置的多個值.

anim.values = @[];

 

它還可以根據一個路徑做動畫.

anim.path = 自己創建的路徑.

 

2.圖片抖動思路:

其實就是做一個左右旋轉的動畫.先讓它往左邊旋轉-5,再往右邊旋轉5度,再從5度旋轉到-5度.

就會有左右搖擺的效果了.

 

具體實現代碼

創建幀動畫

CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];

設置動畫屬性為旋轉

anim.keyPath = @"transform.rotation";

設置屬性值為多個屬性

anim.values = @[@(angle2radio(-5)),@(angle2radio(5)),@(angle2radio(-5))];

設置動畫執行次數

anim.repeatCount = MAXFLOAT;

添加動畫

[_imageView.layer addAnimation:anim forKey:nil];

 

3.根據圓形的路徑做移動的效果.

創建路徑

UIBezierPath *path = [UIBezierPath 

  bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)];

       [path addLineToPoint:CGPointMake(200, 500)];

       

       把路徑設為動畫的屬性

       anim.path = path.CGPath;

 

 


免責聲明!

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



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