iOS動畫:UIView動畫和CALayer動畫(CABasicAnimation、CAKeyframeAnimation的使用)

    iOS中的動畫有兩種實現方式,一種是UIView來實現動畫,另一種動畫是通過CALayer來實現,下面介紹兩種動畫的簡單實現:



一、UIView動畫的實現

   UIView使用Context來實現動畫

關鍵代碼:

//參數1 動畫名稱 參數2 要實現動畫的對象上下文
    
    [UIView beginAnimations:@"attribute" context:_showImageView];
    
    //設置動畫的時間
    [UIView setAnimationDuration:1.0f];
    
    //設置動畫延遲時間
//    [UIView setAnimationDelay:2];
    
    //設置視圖center 實現試圖移動動畫
    _showImageView.center = CGPointMake(100, 100);
    
    //設置alpha值:視圖透明度
    _showImageView.alpha = 0.2f;
    
    //設置背景顏色
    _showImageView.backgroundColor = [UIColor greenColor];
    
    //UIView動畫 設置代理
    [UIView setAnimationDelegate:self];
    
    //動畫將要開始代理方法
    [UIView setAnimationWillStartSelector:@selector(animationWillStart:context:)];
    
    //動畫已經結束代理方法
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    
    //提交動畫設置,執行動畫
    [UIView commitAnimations];



使用Block實現的動畫:

//UIView動畫, 使用Block實現
    [UIView animateWithDuration:1.0f animations:^{
        
        //通過設置translation 實現視圖的偏移
        if ([self.mySwitch isOn]) {
            
            //基於上一次的translation
            _showImageView.transform = CGAffineTransformTranslate(_showImageView.transform, 50, 0);
        } else {
            
            //基於原始的translation
            _showImageView.transform = CGAffineTransformMakeTranslation(-50, 0);
        }
    }];



二、CALayer動畫的實現

CABasic動畫的實現:根據初始位置和結束位置確定動畫

//CABasic 有兩個屬性 fromValue 動畫開始值,toValue動畫結束值
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation1 setDuration:2];
    animation1.fromValue = [NSValue valueWithCGPoint:CGPointMake(150, 150)];
    animation1.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
    [_imageView.layer addAnimation:animation1 forKey:@"position"];



創建一組動畫:

//創建組動畫對象
    CAAnimationGroup *group = [CAAnimationGroup animation];
    
    //CABasic動畫
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
    animation1.fromValue = @1.5;
    animation1.toValue = @0.5;
    
    //關鍵幀動畫
    CAKeyframeAnimation *animation2 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation2.values = @[[NSValue valueWithCGPoint:CGPointMake(100, 100)],
                         [NSValue valueWithCGPoint:CGPointMake(200, 150)],
                         [NSValue valueWithCGPoint:CGPointMake(100, 200)],
                         [NSValue valueWithCGPoint:CGPointMake(200, 250)]];
    
    //group添加動畫數組,group中動畫對象併發執行
    [group setAnimations:@[animation1, animation2]];
    [group setDuration:4.0f];
    [_imageView.layer addAnimation:group forKey:@"group"];




完整的工程和代碼見:https://github.com/winann/iOS-Animation


工程中的動畫實現方法比較全,而且都有註釋,大家可以直接把工程下載下來,邊看邊練習一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章