//
// ViewController.m
#import "ViewController.h"
// 一秒转6°
#define perSecondA 6
// 一分钟转6°
#define perMinuteA 6
// 一小时转30°
#define perHourA 30
// 每分钟时针转多少度
#define perMinuteHourA 0.5
// 角度转弧度
#define angle2radian(a) (a / 180.0 * M_PI)
@interface ViewController ()
/**
* 钟表图片
*/
@property (weak, nonatomic) IBOutlet UIImageView *clockView;
@property(nonatomic,weak) CALayer *secondLayer;
@property(nonatomic,weak) CALayer *minuteLayer;
@property(nonatomic,weak) CALayer *hourLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 添加时针
[self setupHourLayer];
// 添加分针
[self setupMinuteLayer];
// 添加秒针
[self setupSecondLayer];
// 添加定时器
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
[self timeChange];
}
/**
* 定时器会调用的方法
*/
- (void)timeChange
{
// 获取当前系统时间
// 1.获取当前日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
// 2.获取日期的组件:年月日时分秒
// components: 需要获取的日期组件
// fromDate: 获取哪个日期的组件
NSDateComponents *cmp = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:[NSDate date]];
// 计算秒钟转多少度
CGFloat secondA = cmp.second * perSecondA;
// 旋转秒针
_secondLayer.transform = CATransform3DMakeRotation(angle2radian(secondA), 0, 0, 1);
// 计算分针转多少度
CGFloat minuteA = cmp.minute * perMinuteA;
_minuteLayer.transform = CATransform3DMakeRotation(angle2radian(minuteA), 0, 0, 1);
// 计算时针转多少度
CGFloat hourA = cmp.hour * perHourA + cmp.minute * perMinuteHourA;
_hourLayer.transform = CATransform3DMakeRotation(angle2radian(hourA), 0, 0, 1);
}
#pragma mark - 添加时针
- (void)setupHourLayer
{
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor blackColor].CGColor;
// 设置锚点
layer.anchorPoint = CGPointMake(0.5, 1);
// 设置position
layer.position = CGPointMake(_clockView.bounds.size.width * 0.5, _clockView.bounds.size.height * 0.5);
layer.bounds = CGRectMake(0, 0, 6, _clockView.bounds.size.width * 0.5 - 40);
layer.cornerRadius = 4;
// 添加
[_clockView.layer addSublayer:layer];
_hourLayer = layer;
}
#pragma mark - 添加分针
- (void)setupMinuteLayer
{
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor blackColor].CGColor;
// 设置锚点
layer.anchorPoint = CGPointMake(0.5, 1);
// 设置position
layer.position = CGPointMake(_clockView.bounds.size.width * 0.5, _clockView.bounds.size.height * 0.5);
layer.bounds = CGRectMake(0, 0, 4, _clockView.bounds.size.width * 0.5 - 20);
layer.cornerRadius = 2;
// 添加
[_clockView.layer addSublayer:layer];
_minuteLayer = layer;
}
#pragma mark - 添加秒针
- (void)setupSecondLayer
{
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor redColor].CGColor;
// 设置锚点
layer.anchorPoint = CGPointMake(0.5, 1);
// 设置position
layer.position = CGPointMake(_clockView.bounds.size.width * 0.5, _clockView.bounds.size.height * 0.5);
layer.bounds = CGRectMake(0, 0, 2, _clockView.bounds.size.width * 0.5 - 20);
// 添加
[_clockView.layer addSublayer:layer];
_secondLayer = layer;
}
@end