实现的效果图如下 :
实现代码如下:
#import "ViewController.h"
//将旋转角度转换为弧度制
#define angleToRadion(angle) ((angle) / 180.0 * M_PI)
//秒针每秒钟转过的角度
#define perSecondAngle 6
//分针每分钟转过的角度
#define perMinuteAngle 6
//时针每小时转过的角度
#define perHourAngle 30
//时针每分钟转过的角度
#define perMuniteHourAngle 0.5
#define kClockWidth 300
#define kClockHeight 250
@interface ViewController ()
//底盘
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@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.0 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
}
- (void)setUpHourLayer
{
//创建图层
CALayer *layer = [CALayer layer];
layer.backgroundColor = [UIColor blackColor].CGColor;
layer.cornerRadius = 8;
//设置图层的锚点
layer.anchorPoint = CGPointMake(0.5, 1);
//设置图层的位置和尺寸
layer.position = CGPointMake(kClockWidth * 0.5, kClockHeight * 0.5);
layer.bounds = CGRectMake(0, 0, 5, kClockWidth * 0.5 - 44);
//将图层添加到父图层中
[self.imgView.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(kClockWidth * 0.5, kClockHeight * 0.5);
layer.bounds = CGRectMake(0, 0, 3, kClockWidth * 0.5 - 34);
//将图层添加到父图层中
[self.imgView.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(kClockWidth * 0.5, kClockHeight * 0.5);
layer.bounds = CGRectMake(0, 0, 1, kClockWidth * 0.5 - 24);
//将图层添加到父图层中
[self.imgView.layer addSublayer:layer];
self.secondLayer = layer;
}
- (void)timeChange
{
//获取日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
//NSLog(@"calendar = %",calendar);
//获取日期组件
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);
}
@end
在实现的过程中,有些小瑕疵...希望可以和大家一起学习!!!