iOS开发核心动画之时钟效果

1. 创建秒针,因秒针与用户无交换,可以用layer

1> 创建秒针

  1. // 创建秒针
  2. CALayer *secondLayer = [CALayer layer];
  3. self.secondLayer = secondLayer;

2> 设置背景色/尺寸/位置

设置锚点(0.5, 0.9)

  1. // 设置背景色
  2. secondLayer.backgroundColor = [UIColor redColor].CGColor;
  3. // 设置尺寸和位置
  4. CGFloat clockViewH = self.clockView.bounds.size.height;
  5. secondLayer.frame = CGRectMake(0, 0, 1, clockViewH * 0.5 - 10);
  6. secondLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
  7. secondLayer.anchorPoint = CGPointMake(0.5, 0.9);

3> 将秒针layer添加到钟表图层上

  1. [self.clockView.layer addSublayer:secondLayer];

4> 开启定时器,每隔1s调用timeChanged方法.来旋转秒针

  1. [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChanged) userInfo:nil repeats:YES];

  2. [self timeChanged];


2. 秒针旋转(实现监听方法 - (void)timeChanged)

1> 获取当前日历

  1. NSCalendar *calendar = [NSCalendar currentCalendar];

2> 获取当前日历的秒数/分钟数/小时数

  1. NSDateComponents *cmp = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour fromDate:[NSDate date]];

3> 获取秒数, 秒针转一圈60秒转360度, 每秒转6度, 计算当前秒数转多少弧度

1度 = 1 / 180.0 * M_PI 弧度

  1. // 计算弧度
  2. CGFloat secondA = second * 6 * (M_PI / 180);
  3. // 旋转
  4. self.secondLayer.transform = CATransform3DMakeRotation(secondA, 0, 0, 1);

3. 同样创建分钟/时针

分钟

  1. - (void)setUpMin
  2. {
  3. // 创建分针
  4. CALayer *minLayer = [CALayer layer];
  5. self.minLayer = minLayer;
  6. // 设置背景色
  7. minLayer.backgroundColor = [UIColor blackColor].CGColor;
  8. // 设置尺寸和位置
  9. CGFloat clockViewH = self.clockView.bounds.size.height;
  10. minLayer.frame = CGRectMake(0, 0, 4, clockViewH * 0.5 - 20);
  11. minLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
  12. minLayer.anchorPoint = CGPointMake(0.5, 1);
  13. [self.clockView.layer addSublayer:minLayer];
  14. }

时针

  1. - (void)setUpHour
  2. {
  3. // 创建时针
  4. CALayer *hourLayer = [CALayer layer];
  5. self.hourLayer = hourLayer;
  6. // 设置背景色
  7. hourLayer.backgroundColor = [UIColor blackColor].CGColor;
  8. // 设置尺寸和位置
  9. CGFloat clockViewH = self.clockView.bounds.size.height;
  10. hourLayer.frame = CGRectMake(0, 0, 4, clockViewH * 0.5 - 30);
  11. hourLayer.position = CGPointMake(clockViewH * 0.5, clockViewH * 0.5);
  12. hourLayer.anchorPoint = CGPointMake(0.5, 1);
  13. [self.clockView.layer addSublayer:hourLayer];
  14. }

4. 在监听方法 - (void)timeChanged 中对分钟/时针进行旋转

分钟 : 分钟转一圈60分钟转360度,每分转6度.旋转角度和秒针一样

  1. // 获取分钟
  2. NSInteger min = cmp.minute;
  3. CGFloat minA = min * 6 * (M_PI / 180);
  4. self.minLayer.transform = CATransform3DMakeRotation(minA, 0, 0, 1);

时针 : 时针转一圈12小时转360度,每小时转30度, 分钟走时针相应也会走,因此将分钟走的时间不足1小时转换成小时,最终时针旋转角度

  1. // 获取时针
  2. NSInteger hour = cmp.hour;
  3. CGFloat hourA = (hour + min / 60) * 30 * (M_PI / 180);
  4. self.hourLayer.transform = CATransform3DMakeRotation(hourA, 0, 0, 1);


原文地址:https://www.cnblogs.com/Xfsrn/p/5000352.html