轉盤抽獎游戲在一般的app中都會有,應該算是一種吸引用戶的一種手段。在項目中集成轉盤抽獎游戲,大都采用h5的方式來實現,但是由於項目需求,需要在app中使用原生來實現轉盤抽獎。實現原理也很簡單,中間的一個圖片姑且把它叫做轉盤好了,當用戶點擊抽獎的時候,跟服務器做一次請求,拿到當前用戶即將獲得的獎品,根據獎品的位置,讓轉盤旋轉對應的時間,和對應的圈數,最后定位到抽獎的位置,轉盤結束轉動,彈窗讓用戶知曉自己的中獎情況。
好了,廢話說到這里,直接上效果圖:

核心代碼:
#define perSection M_PI*2/8
-(void)animationWithSelectonIndex:(NSInteger)index{
[self backToStartPosition];
self.startButton.enabled = NO;
self.needleImgView.image = [UIImage imageNamed:@"lottery_start_needle_noenable"];
self.textImgView.image = [UIImage imageNamed:@"lottery_state_zhong"];
CABasicAnimation *layer = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
//先轉4圈 再選區 順時針(所以這里需要用360-對應的角度) 逆時針不需要
layer.toValue = @((M_PI*2 - (perSection*index +perSection*0.5)) + M_PI*2*4);
layer.duration = 4;
layer.removedOnCompletion = NO;
layer.fillMode = kCAFillModeForwards;
layer.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
layer.delegate = self;
[self.gameBgView.layer addAnimation:layer forKey:nil];
}
-(void)backToStartPosition{
CABasicAnimation *layer = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
layer.toValue = @(0);
layer.duration = 0.001;
layer.removedOnCompletion = NO;
layer.fillMode = kCAFillModeForwards;
[self.gameBgView.layer addAnimation:layer forKey:nil];
}
#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
//設置指針返回初始位置
self.startButton.enabled = YES;
self.needleImgView.image = [UIImage imageNamed:@"lottery_start_needle_enable"];
self.textImgView.image = [UIImage imageNamed:@"lottery_state_start"];
if (self.rotaryEndTurnBlock) {
self.rotaryEndTurnBlock();
}
}
更多源碼請參考demo: https://github.com/qqcc1388/TYRotaryDemo
轉載請標注來源:https://www.cnblogs.com/qqcc1388/p/9121877.html