且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-02 17:41:13

这是我最终所做的。
错误是将动画添加到子层而不是该层。
当仅需要绕圆心旋转时,无需在此处修补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"]; }