1. 程式人生 > >iOS 旋轉動畫的幾種實現方式

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);
    }
}];