使用貝塞爾曲線實現關鍵幀動畫


貝塞爾曲線,可以通過三個點,來確定一條平滑的曲線。在計算機圖形學應該有講。是圖形開發中的重要工具。

image

實現的是一個圖形做圓周運動。不過不是簡單的關鍵幀動畫那樣,是計算出了很多點,當然還是用的關鍵幀動畫,即使用CAKeyframeAnimation。有了貝塞爾曲線的支持,可以賦值給CAKeyframeAnimation 貝塞爾曲線的Path引用。

 

用貝塞爾曲線畫圓,是一種特殊情況,我的做法是通過貝塞爾曲線得到4個半圓的曲線,它們合成的路徑就是整個圓。

以下是動畫部分的代碼:

- (void) doAnimation { 
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"]; 
    animation.duration=10.5f; 
    animation.removedOnCompletion = NO; 
    animation.fillMode = kCAFillModeForwards; 
    animation.repeatCount=HUGE_VALF;// repeat forever 
    animation.calculationMode = kCAAnimationCubicPaced; 
    
    CGMutablePathRef curvedPath = CGPathCreateMutable(); 
    CGPathMoveToPoint(curvedPath, NULL, 512, 184); 
    CGPathAddQuadCurveToPoint(curvedPath, NULL, 312, 184, 312, 384); 
    CGPathAddQuadCurveToPoint(curvedPath, NULL, 310, 584, 512, 584); 
    CGPathAddQuadCurveToPoint(curvedPath, NULL, 712, 584, 712, 384); 
    CGPathAddQuadCurveToPoint(curvedPath, NULL, 712, 184, 512, 184); 
    
    animation.path=curvedPath; 
    
    [flyStarLayer addAnimation:animation forKey:nil]; 
}

 

 

 

quartZ中有CGMutablePathRef,就是為為動畫設置移動路徑的
比如先設個動畫變量

CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath @"position"];
然后設置一個路徑:        

CGMutablePathRef thePath = CGPathCreateMutable();

CGPathMoveToPoint(thePath, NULL, startPoint.x, startPoint.y);

CGPathAddQuadCurveToPoint(thePath, NULL, 150, 30, endPoint.x, endPoint.y);
注:startPoint是起點,endPoint是終點,150,30是x,y軸的控制點,自行調整數值可以出現理想弧度效果

把路徑給動畫變量,設置個動畫時間

bounceAnimation.path = thePath;

bounceAnimation.duration = 0.7;
最后把這個動畫添加給view的layer

[self.layer addAnimation:bounceAnimation forKey @"move"];
大致這樣就OK了


免責聲明!

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



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