iOS 旋轉動畫的幾種實現方式

第一種:使用CABasicAnimated方法

這種方法是最簡單的方法

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@“transform.rotation.z"];
//默認是順時針效果,若將fromValue和toValue的值互換,則爲逆時針效果
animation.fromValue = [NSNumbernumberWithFloat:0.f];
animation.toValue = [NSNumbernumberWithFloat: M_PI *2];
animation.duration = 3;
animation.autoreverses = NO;
animation.fillMode = kCAFillModeForwards;
animation.repeatCount = MAXFLOAT; //如果這裏想設置成一直自旋轉,可以設置爲MAXFLOAT,否則設置具體的數值則代表執行多少次
[view.layer addAnimation:animation forKey:nil];

第二種:使用CGPath繪製路線執行

這種方法用到了CoreGraphics庫中的CGPathAddArc方法

CGMutablePathRef path = CGPathCreateMutable();
//CGPathAddArc函數是通過圓心和半徑定義一個圓,然後通過兩個弧度確定一個弧線。注意弧度是以當前座標環境的X軸開始的。
//需要注意的是由於ios中的座標體系是和Quartz座標體系中Y軸相反的,所以iOS UIView在做Quartz繪圖時,Y軸已經做了Scale爲-1的轉換,因此造成CGPathAddArc函數最後一個是否是順時針的參數結果正好是相反的,也就是說如果設置最後的參數爲1,根據參數定義應該是順時針的,但實際繪圖結果會是逆時針的!
//嚴格的說,這個方法只是確定一箇中心點後,以某個長度作爲半徑,以確定的角度和順逆時針而進行旋轉,半徑最低設置爲1,設置爲0則動畫不會執行
CGPathAddArc(path, NULL, view.centerX, view.centerY, 1, 0,M_PI * 2, 1);
CAKeyframeAnimation * animation = [CAKeyframeAnimationanimationWithKeyPath:@"position"];
    animation.path = path;
    CGPathRelease(path);
    animation.duration = 3;
    animation.repeatCount = 500;
    animation.autoreverses = NO;
    animation.rotationMode =kCAAnimationRotateAuto;
    animation.fillMode =kCAFillModeForwards;
    [layer addAnimation:animation forKey:nil];

 [view.layer addAnimation:animation2 forKey:nil];

前兩種方法是基於CoreAnimation實現的,還有種比較簡單的旋轉動畫:

第三種:使用 animateWithDuration 方法

[UIView animateWithDuration:0.2f animations:^{
    if (self.arrowView) {
    self.arrowView.transform = CGAffineTransformMakeRotation(M_PI);
    }
}];
發佈了63 篇原創文章 · 獲贊 98 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章