
在表盤上繪制(時分秒)三條直線,分別位于不同的圖層,且時針位于最下層,秒針位于最上層
通過storyboard創建表盤,并擁有它
@PRoperty (weak, nonatomic) IBOutlet UIImageView *clockView;使用三個成員變量來保存時分秒三根表針位于的不同圖層
@property (nonatomic, weak) CALayer *secondLayer;@property (nonatomic, weak) CALayer *minuteLayer;@property (nonatomic, weak) CALayer *hourLayer;初始化所用到的常量
//將旋轉角度轉換為弧度制#define angleToRadion(angle) ((angle) / 180.0 * M_PI)//秒針每秒鐘轉過的角度#define perSecondAngle 6//分針每分鐘轉過的角度#define perMinuteAngle 6//時針每小時轉過的角度#define perHourAngle 30//時針每分鐘轉過的角度#define perMuniteHourAngle 0.5設置時分秒三根表針
設置時針
- (void)setUpHourLayer{ //創建圖層 CALayer *layer = [CALayer layer]; layer.backgroundColor = [UIColor blackColor].CGColor; layer.cornerRadius = 8; 設置圖層的錨點 layer.anchorPoint = CGPointMake(0.5, 1); //設置圖層的位置和尺寸 layer.position = CGPointMake(kClockWith * 0.5, kClockWith * 0.5); layer.bounds = CGRectMake(0, 0, 5, kClockWith * 0.5 - 44); //將圖層添加到父圖層中 [self.clockView.layer addSublayer:layer]; self.hourLayer = layer;}設置分針
- (void)setUpMinuteLayer{ CALayer *layer = [CALayer layer]; layer.backgroundColor = [UIColor blackColor].CGColor; layer.cornerRadius = 4; //設置錨點 layer.anchorPoint = CGPointMake(0.5, 1); //設置位置和尺寸 layer.position = CGPointMake(kClockWith * 0.5, kClockWith * 0.5); layer.bounds = CGRectMake(0, 0, 3, kClockWith * 0.5 - 34); //將圖層添加到父圖層中 [self.clockView.layer addSublayer:layer]; self.minuteLayer = layer;}設置秒針
- (void)setUpSecondLayer{ CALayer *layer = [CALayer layer]; layer.backgroundColor = [UIColor redColor].CGColor; //設置錨點 layer.anchorPoint = CGPointMake(0.5, 1); //設置位置和尺寸 layer.position = CGPointMake(kClockWith * 0.5, kClockWith * 0.5); layer.bounds = CGRectMake(0, 0, 1, kClockWith * 0.5 - 24); //將圖層添加到父圖層中 [self.clockView.layer addSublayer:layer]; self.secondLayer = layer;}設置定時器,定時執行動畫
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];設置定時器觸發時調用的方式,添加動畫代碼
- (void)timeChange{ //獲取日歷對象 NSCalendar *calendar = [NSCalendar currentCalendar]; //獲取日期組件 NSDateComponents *components = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour fromDate:[NSDate date]]; //獲取當前的時分秒值 NSInteger second = components.second; NSInteger munite = components.minute; NSInteger hour = components.hour; //計算當前時分秒表針轉過的角度(弧度制) CGFloat secondAngle = angleToRadion(second * perSecondAngle); CGFloat muniteAngle = angleToRadion(munite * perMinuteAngle); CGFloat hourAngle = angleToRadion(hour *perHourAngle + munite * perMuniteHourAngle); //修改時分秒表針位于的圖層的transform屬性,執行隱式動畫 self.secondLayer.transform = CATransform3DMakeRotation(secondAngle, 0, 0, 1); self.minuteLayer.transform = CATransform3DMakeRotation(muniteAngle, 0, 0, 1); self.hourLayer.transform = CATransform3DMakeRotation(hourAngle, 0, 0, 1);}新聞熱點
疑難解答