How to rotate a CAShapeLayer arc around a circle?

I have the two CAShapeLayer s forming the following display:

在这里输入图像描述

They are created with this piece of code:

CALayer *layer = [loadingView layer];
CAShapeLayer *circle = [CAShapeLayer layer];
[circle setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5, loadingView.bounds.size.width - 10, loadingView.bounds.size.height - 10)] CGPath]];
[circle setStrokeColor:[UIColorFromRGB(0xffffff, .15) CGColor]];
[circle setLineWidth:5];
[circle setFillColor:[[UIColor clearColor] CGColor]];
[layer addSublayer:circle];

CAShapeLayer *arc = [CAShapeLayer layer];
[arc setPath:[[UIBezierPath bezierPathWithArcCenter:CGPointMake(27, 27) radius:22 startAngle:1.25*M_PI endAngle:1.75*M_PI clockwise:YES] CGPath]];
[arc setStrokeColor:[UIColorFromRGB(0xffffff, .8) CGColor]];
[arc setLineWidth:5];
[arc setFillColor:[[UIColor clearColor] CGColor]];
[layer addSublayer:arc];

I'd like for the smaller, opaque arc to retain its size and spin around the circle indefinitely. I've tried applying a number of transform.rotation animations that I found on other answers, however the arc ends up spinning into unpredictable directions.

I've also tried raising strokeStart and strokeEnd of the arc at the same rate, which gets the effect I want at first but is unable to proceed cyclically due to the nature of those properties.

That being so, how to perform this effect?


Your best bet here would be to rotate your entire circle. Rotate loadingView around its center and you'll get the effect you want. You'll gain the added benefit of being able to even modify the stroke length very easily without messing up your rotation.


By default, the origin of the coordinate system in a shape layer is at the point (0,0), and its bounds have 0×0 dimensions; when you give it a path, neither of those attributes change automatically. The arc you're giving it is centered at (27, 27), so when you rotate the layer the drawn arc is rotating around the layer's actual center, which is a point 27 points above and to the left of the center of the arc.

Your best option is to change the way you're creating the arc shape and positioning its layer. Instead of creating the Bézier path with a center of (27, 27), give it a center of (0, 0)—ie the origin of the layer—and set the arc layer's position to (27, 27) within its parent layer.

链接地址: http://www.djcxy.com/p/74260.html

上一篇: CAShapeLayer的性能?

下一篇: 如何旋转一个圆形的CAShapeLayer弧?