抽獎轉盤的核心是讓一張大圖持續旋轉,並在約定時間內停下。這裡用兩個定時器分工:一個以極短間隔不斷累加角度驅動動畫,另一個每秒遞減倒計時,時間到就關閉前者。
效果:

#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *panImageView;
/** 累積角度 */
@property (nonatomic, assign) int angle;
/** 驅動旋轉的定時器 */
@property (strong, nonatomic) NSTimer *timer;
/** 倒計時定時器 */
@property (strong, nonatomic) NSTimer *timeTick;
/** 剩餘秒數 */
@property (nonatomic, assign) int timeNumber;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.timeNumber = 3;
// 每 0.01 秒推進一次角度
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(startAnimation)
userInfo:nil
repeats:YES];
// 每秒遞減一次倒計時
self.timeTick = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timeFireMethod)
userInfo:nil
repeats:YES];
}
- (void)startAnimation {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationDelegate:self];
_panImageView.animationRepeatCount = 1;
self.angle += 1000;
// 以中心為旋轉錨點:(0,0) 左上角,(0.5,0.5) 正中間
self.panImageView.layer.anchorPoint = CGPointMake(0.5, 0.5);
self.panImageView.transform = CGAffineTransformMakeRotation(self.angle * (M_PI / 180.0f));
[UIView commitAnimations];
}
- (void)timeFireMethod {
self.timeNumber--;
if (self.timeNumber == 0) {
[self.timer invalidate]; // 時間到,停止旋轉
}
}
@end
anchorPoint 決定了旋轉中心,設為 (0.5, 0.5) 才能繞盤心轉動;角度以「度」累加後再乘 M_PI / 180 轉為弧度,是因為 CGAffineTransformMakeRotation 只接受弧度。另外定時器有兩處務必留意:一是必须 invalidate 釋放,否則 target 無法回收;二是精細流暢的轉盤更推薦用 Core Animation 的旋轉動畫配合 CAAnimation 的 easing 曲線,比定時器逐幀推動更省電也更順滑。