有这样的需求,在椭圆的轨迹上放了几个物体,点其中一个,沿着椭圆的轨迹,旋转一定的角度。
一个物体沿着椭圆轨迹转一圈好实现,但是沿着椭圆轨迹走其中的一段,却不好实现,有哪位大侠有好的实现思路?
可以用UIBezierPath
把要走的轨迹画出来,然后用CAKeyframeAnimation
设置path
属性,这样应该可以吧。
update:
用bezierPath
画椭圆的一部分,可以试试以下代码:
- (void)drawRect:(CGRect)rect {
CGFloat x = 50, y = 50, width = 200, height = 100, startAngle = M_PI / 4, endAngle = M_PI * 3 / 2;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGPoint center = CGPointMake(x + width / 2.0, y + height / 2.0);
UIBezierPath* clip = [UIBezierPath bezierPathWithArcCenter:center
radius:MAX(width, height)
startAngle:startAngle
endAngle:endAngle
clockwise:YES];
[clip addLineToPoint:center];
[clip closePath];
[clip addClip];
UIBezierPath *arc = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(x, y, width, height)];
[[UIColor blackColor] setStroke];
[arc stroke];
CGContextRestoreGState(context);
}
效果:
我参考了这个答案。
另外,如同楼下所说,bezierPath
的确跟椭圆不是完全相同的,不过视觉上就没有那么大差别啦~ 用参数方程的方法算坐标也可以的。
bezier 和 arc 不是等价的。详见此文:
http://www.redblobgames.com/articles/curved-paths/
椭圆实际上就是在x轴或y轴拉伸过的正圆,可以用参数方程计算
x = a cos(t)
y = b sin(t)
其中 a 是x半轴长, b 是y半轴长