Calculating angle of clock hands


/ Published in: Objective C
Save to your folder(s)

Simple calculation for a clock


Copy this code and paste it in your HTML
  1. @property (weak, nonatomic) IBOutlet UIImageView *hourHands;
  2. @property (weak, nonatomic) IBOutlet UIImageView *minuteHands;
  3. @property (weak, nonatomic) IBOutlet UIImageView *secondHands;
  4. @property (weak, nonatomic) NSTimer *timer;
  5.  
  6. - (void)viewDidLoad
  7. {
  8. [super viewDidLoad];
  9. self.secondHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
  10. self.minuteHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
  11. self.hourHands.layer.anchorPoint = CGPointMake(0.5f, 0.9f);
  12.  
  13. self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateClockHands) userInfo:nil repeats:YES];
  14.  
  15. // Make sure user does not see uncalibrated hands at 0,0 position.
  16. [self updateClockHands];
  17. }
  18.  
  19. -(void) updateClockHands
  20. {
  21. NSCalendar *cal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
  22. NSUInteger units = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
  23.  
  24. NSDateComponents *components = [cal components:units fromDate:[NSDate date]];
  25.  
  26. CGFloat hoursAngle = (components.hour /12.0) * M_PI * 2.0;
  27. CGFloat minsAngle = (components.minute / 60.0) * M_PI * 2.0;
  28. CGFloat secsAngle = (components.second / 60.0) * M_PI * 2.0;
  29.  
  30. // Now you can adjust the hands of a clock
  31. // Assuming hourHands, minuteHands, secondHands are UIImageview's and are setup as properties in .m
  32. self.hourHands.transform = CGAffineTransformMakeRotation(hoursAngle);
  33. self.minuteHands.transform = CGAffineTransformMakeRotation(minsAngle);
  34. self.secondHands.transform = CGAffineTransformMakeRotation(secsAngle);
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.