Object angle based on current time

前端 未结 2 1079
甜味超标
甜味超标 2021-02-06 19:49

Listen carefully, because this is specific. I\'m trying to make an analog clock in iPhone SDK. I\'ve been trying to accomplish this for three weeks now, I\'ve asked five quest

2条回答
  •  不思量自难忘°
    2021-02-06 20:43

    three weeks? Seriously?
    my clock is very fugly but it is a clock, and it looks good enough to guess the current time from it.

    static inline float PGVmyRadians(double degrees) { return degrees * M_PI / 180; }
    
    - (void)drawRect:(CGRect)rect {
        CGFloat boundsWidth = self.bounds.size.width;
        CGFloat boundsHeight = self.bounds.size.height;
        CGPoint center = CGPointMake(boundsWidth/2, boundsHeight/2);
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextClearRect(context, self.bounds);
        CGContextSetFillColorWithColor(context, [UIColor magentaColor].CGColor);
        CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextSetLineWidth(context, 10);
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextAddArc(context, boundsWidth/2, boundsHeight/2, boundsWidth/2, PGVmyRadians(0), PGVmyRadians(360), 0);
    
        NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
        NSInteger seconds = [dateComponents second];
        NSInteger minutes = [dateComponents minute];
        NSInteger hour = [dateComponents hour];
    
        if (hour > 12) {
            hour -= 12;
        }
    
        CGFloat angleSec = ((seconds - 15) / 60.0) * 360.0;
        CGFloat thetaSec = PGVmyRadians(angleSec);
        CGFloat lengthSec = 0.9 * boundsHeight/2;
        CGFloat Xsec = center.x + lengthSec * cos(thetaSec);
        CGFloat Ysec = center.y + lengthSec * sin(thetaSec);
    
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddLineToPoint(context, Xsec, Ysec);
    
        CGFloat angleMin = ((minutes - 15) / 60.0) * 360.0;
        CGFloat thetaMin = PGVmyRadians(angleMin);
        CGFloat lengthMin = 0.7 * boundsHeight/2;
        CGFloat Xmin = center.x + lengthMin * cos(thetaMin);
        CGFloat Ymin = center.y + lengthMin * sin(thetaMin);
    
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddLineToPoint(context, Xmin, Ymin);
    
        CGFloat angleHour = ((hour - 3) / 12.0) * 360.0;
        CGFloat thetaHour = PGVmyRadians(angleHour);
        CGFloat lengthHour = 0.5 * boundsHeight/2;
        CGFloat Xhour = center.x + lengthHour * cos(thetaHour);
        CGFloat Yhour = center.y + lengthHour * sin(thetaHour);
    
        CGContextMoveToPoint(context, center.x, center.y);
        CGContextAddLineToPoint(context, Xhour, Yhour);
        CGContextStrokePath(context);
    }
    

提交回复
热议问题