标签:
1. 创建秒针,因秒针与用户无交换,可以用layer
1> 创建秒针
// 创建秒针
CALayer *secondLayer = [CALayer layer];
self.secondLayer = secondLayer;
2> 设置背景色/尺寸/位置
设置锚点(0.5, 0.9)
// 设置背景色
secondLayer.backgroundColor = [UIColor redColor].CGColor;
// 设置尺寸和位置
CGFloat clockViewH = self.clockView.bounds.size.height;
secondLayer.frame = CGRectMake(0, 0, 1, clockViewH * 0.5 - 10);
secondLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
secondLayer.anchorPoint = CGPointMake(0.5, 0.9);
3> 将秒针layer添加到钟表图层上
[self.clockView.layer addSublayer:secondLayer];
4> 开启定时器,每隔1s调用timeChanged方法.来旋转秒针
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChanged) userInfo:nil repeats:YES];
[
self
timeChanged];
2. 秒针旋转(实现监听方法 - (void)timeChanged)
1> 获取当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
2> 获取当前日历的秒数/分钟数/小时数
NSDateComponents *cmp = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour fromDate:[NSDate date]];
3> 获取秒数, 秒针转一圈60秒转360度, 每秒转6度, 计算当前秒数转多少弧度
1度 = 1 / 180.0 * M_PI 弧度
// 计算弧度
CGFloat secondA = second * 6 * (M_PI / 180);
// 旋转
self.secondLayer.transform = CATransform3DMakeRotation(secondA, 0, 0, 1);
3. 同样创建分钟/时针
分钟
- (void)setUpMin
{
// 创建分针
CALayer *minLayer = [CALayer layer];
self.minLayer = minLayer;
// 设置背景色
minLayer.backgroundColor = [UIColor blackColor].CGColor;
// 设置尺寸和位置
CGFloat clockViewH = self.clockView.bounds.size.height;
minLayer.frame = CGRectMake(0, 0, 4, clockViewH * 0.5 - 20);
minLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
minLayer.anchorPoint = CGPointMake(0.5, 1);
[self.clockView.layer addSublayer:minLayer];
}
时针
- (void)setUpHour
{
// 创建时针
CALayer *hourLayer = [CALayer layer];
self.hourLayer = hourLayer;
// 设置背景色
hourLayer.backgroundColor = [UIColor blackColor].CGColor;
// 设置尺寸和位置
CGFloat clockViewH = self.clockView.bounds.size.height;
hourLayer.frame = CGRectMake(0, 0, 4, clockViewH * 0.5 - 30);
hourLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
hourLayer.anchorPoint = CGPointMake(0.5, 1);
[self.clockView.layer addSublayer:hourLayer];
}
4. 在监听方法 - (void)timeChanged 中对分钟/时针进行旋转
分钟 : 分钟转一圈60分钟转360度,每分转6度.旋转角度和秒针一样
// 获取分钟
NSInteger min = cmp.minute;
CGFloat minA = min * 6 * (M_PI / 180);
self.minLayer.transform = CATransform3DMakeRotation(minA, 0, 0, 1);
时针 : 时针转一圈12小时转360度,每小时转30度, 分钟走时针相应也会走,因此将分钟走的时间不足1小时转换成小时,最终时针旋转角度
// 获取时针
NSInteger hour = cmp.hour;
CGFloat hourA = (hour + min / 60) * 30 * (M_PI / 180);
self.hourLayer.transform = CATransform3DMakeRotation(hourA, 0, 0, 1);
标签:
原文地址:http://www.cnblogs.com/Xfsrn/p/5000352.html