中心点からの角度 2011/10/22

以前書いた記事から プログラマメモ2: 中心点からの角度
今度は、objective-cで作成してみました。

#import "MyView.h" @implementation MyView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } /* タッチイベント:touchesBegan */ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self setNeedsDisplay]; } /* タッチイベント:touchesBegan */ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self setNeedsDisplay]; } /* タッチイベント:touchesMoved */ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // CGPoint touchPoint = [[touches anyObject] locationInView:self]; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); float cx = self.bounds.size.width/2; float cy = self.bounds.size.height/2; // 文字色 CGContextSetRGBFillColor(context, 0, 0, 0, .2); // 線色 CGContextSetRGBStrokeColor(context, 0, 0, 0, .2); double degree; { // 初期値(中心値からの角度をもとめる) int mx = touchPoint.x - cx; int my = touchPoint.y - cy; if (mx == 0 && my == 0) { degree = 0; } else { degree = atan2(my, mx) * (180 / M_PI); } } { // line CGContextMoveToPoint(context, cx, cy); CGContextAddLineToPoint(context, touchPoint.x,touchPoint.y); CGContextStrokePath(context); } { // string NSString *str1 = [NSString stringWithFormat:@"x=%.0f, y=%.0f", touchPoint.x, touchPoint.y]; NSString *str2 = [NSString stringWithFormat:@"degree:%.0f", degree]; NSString *str3 = [NSString stringWithFormat:@"角度(0~360):%.0f", degree < 0 ? (180 + degree) + 180:degree]; UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; [str1 drawAtPoint:CGPointMake(touchPoint.x, touchPoint.y) withFont:font]; [str2 drawAtPoint:CGPointMake(touchPoint.x, touchPoint.y+20) withFont:font]; [str3 drawAtPoint:CGPointMake(touchPoint.x, touchPoint.y+40) withFont:font]; } } @end

: