iOS: derive angle of tap point given a circle

守給你的承諾、 提交于 2019-12-01 10:27:23
Lyndsey Scott

I just noticed some errors in this solution I'd mentioned in the comments, but it's generally what you need...

I recommend getting the angle between your tap point and your circle's frame's center then implementing a getArea function to get the particular area tapped within your circle, ex:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [touches anyObject];
    CGPoint tapPoint = [touch locationInView:self.view];
    CGFloat angle = [self angleToPoint:tapPoint];

    int area = [self sectionForAngle:angle];
}

- (float)angleToPoint:(CGPoint)tapPoint
{
    int x = self.circle.center.x;
    int y = self.circle.center.y;
    float dx = tapPoint.x - x;
    float dy = tapPoint.y - y;
    CGFloat radians = atan2(dy,dx); // in radians
    CGFloat degrees = radians * 180 / M_PI; // in degrees

    if (degrees < 0) return fabsf(degrees);
    else return 360 - degrees;
}

- (int)sectionForAngle:(float)angle
{
    if (angle >= 0 && angle < 60) {
        return 1;
    } else if (angle >= 60 && angle < 120) {
        return 2;
    } else if (angle >= 120 && angle < 180) {
        return 3;
    } else if (angle >= 180 && angle < 240) {
        return 4;
    } else if (angle >= 240 && angle < 300) {
        return 5;
    } else {
        return 6;
    }
}
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         let touch = touches.first
         let tapPoint = touch?.location(in: self)
         let distance = distanceWithCenter(center: circleCenter,SCCenter: tapPoint!)
                if distance <= radius {
                 let angle  = angleToPoint(tapPoint: tapPoint!)
                 print(angle)
        }


func angleToPoint(tapPoint:CGPoint) -> CGFloat{
            let dx =  circleCenter.x - tapPoint.x
            let dy =  circleCenter.y - tapPoint.y
            let radians = atan2(dy, dx) + π // Angel in radian

            let degree = radians * (180 / π)  // Angel in degree
            print("angle is off = \(degree)")
            return degree
        }

You got the angle now check in which section it belong.You can figure it out by comparision.If you face any problem please let me know .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!