首页 > 技术文章 > iOS大转盘抽奖

hxwj 2016-03-02 12:40 原文

功能

点击大转盘旋转后固定到某个自己可以确定的位置

结构

转盘,开始按钮,指针

技术

CADisplayLink不停重绘,CGAffineTransform旋转,简单数学公式

核心代码

1.使用CADisplayLink不停重绘旋转底盘

// 开始转动(一直不停的转动)
- (void)startRotate
{
    
    CADisplayLink* link = [CADisplayLink displayLinkWithTarget:self selector:@selector(Rotate)];
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.link = link;
}

//
- (void)Rotate

{
    //每次旋转6°
    self.rotateWheel.transform = CGAffineTransformRotate(self.rotateWheel.transform, M_PI * 2 / 12/ 60 );
}

2.点击开始执行旋转动画,

  if (![self.rotateWheel.layer animationForKey:@"zhuandong"]) {
        
        CABasicAnimation* animation = [[CABasicAnimation alloc] init];
        
        animation.keyPath = @"transform.rotation";
        animation.toValue = @(2 * M_PI * 5 - M_PI*2/12*(13-self.numberIndex));
        animation.duration = 5;
        
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;
        
        [self.rotateWheel.layer addAnimation:animation forKey:@"zhuandong"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(animation.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.rotateWheel.transform = CGAffineTransformMakeRotation(M_PI*2/12*(13-self.numberIndex));
            self.link.paused = YES;
            
            [self.rotateWheel.layer removeAnimationForKey:@"zhuandong"];
            
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"恭喜你!被骗了!!!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
            if (_delegate && [_delegate respondsToSelector:@selector(LuckyDrawViewDidFinishWidthIndex:)]) {
                [_delegate LuckyDrawViewDidFinishWidthIndex:self.numberIndex];
            }
            self.numberIndex = 1;
            
        });
    }

3.其间控制转盘最后停留的位置用一个变量控制就行了

@property (nonatomic,assign)NSInteger numberIndex;

效果图

demo链接:http://pan.baidu.com/s/1dDPimiP

推荐阅读