使用CABasicAnimation围绕其中心旋转CAShapeLayer弧

问题描述:

我有一个使用CAShapeLayer绘制的圆弧,并且希望它绕圆心旋转。我正在尝试使用 transform.rotation属性上的CABasicAnimation获取此动画。但是旋转似乎发生在与圆心不同的点上。

I have an arc that I have drawn using CAShapeLayer and I want it to rotate around the circle's center. I am trying to get this animation using a CABasicAnimation on the 'transform.rotation' property. But the rotation seems is happening about a point that is not the same as the circle's center.

-(void)drawRect:(CGRect)rect{
 int radius = 100;
 CAShapeLayer *circle = [CAShapeLayer layer];
 circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
 circle.fillColor = [UIColor orangeColor].CGColor;
 circle.strokeColor = [UIColor blueColor].CGColor;
 circle.lineWidth = 5;
 circle.strokeStart = 0.0f;
 circle.strokeEnd = 0.1f;
 [self.layer addSublayer:circle];

 CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
 spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
 spinAnimation.duration = 4;
 spinAnimation.repeatCount = INFINITY;
 [circle addAnimation:spinAnimation forKey:@"indeterminateAnimation"];
} 

我知道这是一个老问题,但出路在哪里。我通过设置图层的边界或锚点进行了很多修改,但它尚未绕中心旋转。

I know its an old problem, but whats the way out. I have tinkered a lot by setting the layer's bounds or the anchor point but it doesn't rotate about the center yet.

circle.bounds = self.frame;

这是将视图添加到视图控制器的方式。

Here is how I add the view to the view controller.

[self.view addSubview:[[ProgressIndicator alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]];


这是我最终所做的。
错误是将动画添加到子层而不是该层。
当仅需要绕圆心旋转时,无需在此处修补anchorPoint或位置。

This is what I eventually did. The mistake was to add the animation to the sublayer and not the layer. There is no need to tinker with anchorPoint or position here when the rotation is just needed about the center of the circle.

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
       self.backgroundColor = [UIColor clearColor];

       int radius = 50;
       CAShapeLayer *circle = [CAShapeLayer layer];
       circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
       circle.fillColor = [UIColor clearColor].CGColor;
       circle.strokeColor = [UIColor blueColor].CGColor;
       circle.lineWidth = 5;
       circle.strokeStart = 0.0f;
       circle.strokeEnd = 0.1f;

       [self.layer addSublayer:circle];
    }

   return self; }

- (void)drawRect:(CGRect)rect {

    CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
    spinAnimation.duration = 4;
    spinAnimation.repeatCount = INFINITY;

    [self.layer addAnimation:spinAnimation forKey:@"indeterminateAnimation"]; }