前言:最近公司項目有個需求,需要實現(xiàn)讓一個view沿著橢圓軌跡做動畫,效果實現(xiàn)后,就自己封裝做了一個小demo,使用更方便。先看效果:

效果圖中的白色橢圓軌跡線其實是用貝塞爾曲線畫出來的,為了清晰的看出來運動的軌跡。其實項目中是不顯示軌跡線的,也就是小球是懸空運動的。若不需要刪除掉即可。
**
實現(xiàn)步驟:
**
1.首先設(shè)定關(guān)鍵幀動畫CAKeyframeAnimation的一些屬性,比如運動時間和重復(fù)次數(shù)和calculationMode模式,我們選擇kCAAnimationPaced 使得動畫均勻進行。
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
pathAnimation.duration = 5.0;
pathAnimation.repeatCount = 2;
2.設(shè)定好關(guān)鍵幀動畫的path,即一個橢圓形的路徑。需要使用CGPathAddArc,CGPathAddArc經(jīng)常用于畫正圓,比如下面就是一個正圓,各個參數(shù)的意義:
//160,200為圓心,100為半徑 (startAngle,endAngle)為起始角度和結(jié)束角度,1為順時針,0 為逆時針
CGPathAddArc(curvedPath, NULL, 160,200, 100, startAngle, endAngle, 0);
需要注意的是由于iOS中的坐標(biāo)體系是和Quartz坐標(biāo)體系中Y軸相反的,所以iOS UIView在做Quartz繪圖時,Y軸已經(jīng)做了Scale為-1的轉(zhuǎn)換,因此造成CGPathAddArc函數(shù)最后一個是否是順時針的參數(shù)結(jié)果正好是相反的,也就是說如果設(shè)置最后的參數(shù)為YES,根據(jù)參數(shù)定義應(yīng)該是順時針的,但實際繪圖結(jié)果會是逆時針的!
我們需要畫的是橢圓啊,別急,接下來稍作更改即可。正圓第二個參數(shù)默認為NULL,我們要改成橢圓,
//短半軸和長半軸的比例
float radiuscale = 0.5;
//橢圓頂點的坐標(biāo)值
CGFloat origin_x = self.frame.size.width/2;
CGFloat origin_y = self.frame.size.height/2;
//長半軸的長
CGFloat radiusX = 100;
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGAffineTransform t2 = CGAffineTransformConcat(CGAffineTransformConcat(
CGAffineTransformMakeTranslation(-origin_x, -origin_y),
CGAffineTransformMakeScale(1, radiuscale)),
CGAffineTransformMakeTranslation(origin_x, origin_y));
CGPathAddArc(curvedPath, &t2, origin_x, origin_y, radiusX,startAngle,endAngle, 1);
pathAnimation.path = curvedPath;
CGPathRelease(curvedPath);
好了,至此,動畫的軌跡和屬性都寫好了。添加到view上就ok了。
3.貝塞爾畫橢圓
如果是整個橢圓的話,只需要設(shè)定好理想中的橢圓的外切圓即可。
//整個橢圓
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
UIBezierPath *arc = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(origin_x-100, origin_y-50, 200, 100)];
[[UIColor whiteColor] setStroke];
[arc stroke];
CGContextRestoreGState(context);
**總結(jié): 希望本文能對你有幫助。如果你有更好的想法,歡迎和我交流! **
demo地址:https://github.com/xiaochenyi/CircleAnimateDemo