旋转轮仅在每个90度扇区停止

时间:2016-07-31 11:55:43

标签: ios objective-c

我制作了26个扇区的旋转轮。我希望旋转轮在任何扇区随机停止,而它只在每90度扇区停止(在扇区#0,6,13,20)。这是我的代码段。

// an ivar for your class:
BOOL animating;

- (void) spinWithOptions: (UIViewAnimationOptions) options {
   // this spin completes 360 degrees every 2 seconds
   [UIView animateWithDuration: 0.5f
                         delay: 0.0f
                       options: options
                    animations: ^{
                       self.imageToMove.transform = CGAffineTransformRotate(imageToMove.transform, M_PI / 2);
                    }
                    completion: ^(BOOL finished) {
                       if (finished) {
                          if (animating) {
                             // if flag still set, keep spinning with constant speed
                             [self spinWithOptions: UIViewAnimationOptionCurveLinear];
                          } else if (options != UIViewAnimationOptionCurveEaseOut) {
                             // one last spin, with deceleration
                             [self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
                          }
                       }
                    }];
}

- (void) startSpin {
   if (!animating) {
      animating = YES;
      [self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
   }   
}

- (void) stopSpin {
    // set the flag to stop spinning after one last 90 degree increment
    animating = NO;
}

请告诉我每次旋转时如何让它随机停止。

1 个答案:

答案 0 :(得分:0)

我已经制定了以下随机选择片段的方法。

numberOfSections是车轮中的分段数。angleSize的计算如下:

angleSize = 2 * M_PI / numberOfSections;

  • (void)pressSpin {

    CGFloat randValue= (arc4random() % numberOfSections)+numberOfSections;
    angleRotate =  (randValue * angleSize)*2;
    CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    spinAnimation.fromValue = [NSNumber numberWithFloat:angleSize];
    spinAnimation.toValue = [NSNumber numberWithFloat:angleSize+angleRotate];
    spinAnimation.duration = 2.0f;
    spinAnimation.cumulative = YES;
    spinAnimation.additive = YES;
    spinAnimation.removedOnCompletion = NO;
    spinAnimation.delegate = self;
    spinAnimation.timingFunction = [CAMediaTimingFunction
                                    functionWithName:kCAMediaTimingFunctionEaseOut];
    spinAnimation.fillMode = kCAFillModeForwards;
    [container.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
    
    }