最近做一款手表类的软件 突然想模拟一个时钟
结果.......
看代码实现吧
-(void)showTime
{
//通过图片设定个表盘
UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
[imageview setImage:[UIImage imageNamed:@"watch.jpg"]];
imageview.center = self.view.center;
[self.view addSubview:imageview];
//在这里我们创建一个UIView 背景是透明色的
//由于手机屏幕角度规定和时钟角度有所不同,所以需要对角度进行调整。
UIView *clearView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
[clearView setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
clearView.center = self.view.center;
[self.view addSubview:clearView];
//制作钟表的时针 分针秒针
self.secondHand = [[UIView alloc]initWithFrame:CGRectMake(0,0, 150, 3)];
self.secondHand.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.width/2);
[self.secondHand setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.7]];
[clearView addSubview:self.secondHand];
self.minuteHand = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 130, 4)];
self.minuteHand.center = CGPointMake(self.view.frame.size.width/2,self.view.frame.size.width/2);
[self.minuteHand setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.7]];
[clearView addSubview:self.minuteHand];
self.hourHand = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 5)];
self.hourHand.center = CGPointMake(self.view.frame.size.width/2,self.view.frame.size.width/2);
[self.hourHand setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.7]];
[clearView addSubview:self.hourHand];
//我们把表针都添加在了clearView上了
//在这里我们直接旋转clearView就可以了
//M_PI_2顺时针旋转90度
clearView.transform = CGAffineTransformRotate(clearView.transform, M_PI_2);
这就是一个视图的锚点的位置
锚点事项对于自身的按比例分配
//设置锚点(一般都用于动画的实现)
//注意:锚点是在自身上找
self.secondHand.layer.anchorPoint = CGPointMake( .8, .5);
self.minuteHand.layer.anchorPoint = CGPointMake(.8, .5);
self.hourHand.layer.anchorPoint = CGPointMake(.8, .5);
//设定一个计时器一秒监听一次
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tick) userInfo:nil repeats:YES];
[self tick];
- (void)tick {
//获取当前时间
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
//与角度0 的夹角
/*
例如 当前是30秒的时候 30/60 *180度(M_PI)*2 = 180;
*/
CGFloat hoursAngle = (components.hour / 12.0) *M_PI * 2.0;
CGFloat minsAngle = (components.minute / 60.0) * M_PI * 2.0;
CGFloat secsAngle = (components.second / 60.0) * M_PI * 2.0;
//旋转的角度
self.hourHand.transform = CGAffineTransformMakeRotation(hoursAngle);
self.minuteHand.transform = CGAffineTransformMakeRotation(minsAngle);
self.secondHand.transform = CGAffineTransformMakeRotation(secsAngle);
}
实现的效果