iPhone:如何量化被触摸物体的位置

时间:2012-08-28 09:24:53

标签: iphone touch geometry quantization

大家都很聪明! 我想为iOS应用程序创建一个触摸界面,允许用户在屏幕上拖动对象。 但是,此对象应限制为沿圆周移动,以便如果用户试图将对象拖到该路径之外,它将粘贴到该圆的最近点。 我做了一些iPhone编程,但我的数学很差。请帮忙!

1 个答案:

答案 0 :(得分:1)

您所要做的就是将视图的框架设置为遵循圆的等式(形式为(x-a)^2 + (y-b)^2 = r^2)。一旦检测到触摸点,就可以根据触摸点的x或y坐标限制视图的帧(两种方式都相同)。

#define circleRadius 60.0 // r in the above eqtn
#define circlesCenter_X 160.0 // a in the above eqtn
#define circlesCenter_Y 200.0 // b in the above eqtn
#define circleCenter_y(x) sqrtf(circleRadius*circleRadius - (x-circlesCenter_X)*(x-circlesCenter_X))

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event touchesForView:firstPieceView] anyObject];
    CGPoint previousLocation = [touch previousLocationInView:self.view];
    CGPoint location = [touch locationInView:self.view];
    CGFloat delta_x = previousLocation.x - location.x; // constrained by x in this eg.
    CGFloat newX = firstPieceView.center.x-delta_x;
    // do limit the view's x-coordinate for possible solutions
    if(newX<circlesCenter_X - circleRadius)
        newX = circlesCenter_X - circleRadius;
    if(newX>circlesCenter_X + circleRadius)
        newX = circlesCenter_X + circleRadius;
    firstPieceView.center = CGPointMake(newX, circleCenter_y(newX)*(location.y>=circlesCenter_Y?1:-1) + circlesCenter_Y);
}

编辑 - 更好的解决方案:

#define circleRadius 60.0 // r in the above eqtn
#define circlesCenter_X 160.0 // a in the above eqtn
#define circlesCenter_Y 200.0 // b in the above eqtn
#define slope(x,y) (y-circlesCenter_Y)/(x-circlesCenter_X)
#define pointOnCircle_X(m) circleRadius/(sqrtf(m*m + 1))

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event touchesForView:self.view] anyObject];
    CGPoint location = [touch locationInView:self.view];
    CGFloat slope;
    CGPoint pointOnCircle;
    if(location.x==circlesCenter_X){// case for infinite slope
        pointOnCircle.x = circlesCenter_X;
        if(location.x<circlesCenter_X){
            pointOnCircle.y = circlesCenter_Y - circleRadius;
        }else{
            pointOnCircle.y = circlesCenter_Y + circleRadius;
        }
    }else{
        slope = slope(location.x,location.y);
        if(location.x<circlesCenter_X){
            pointOnCircle.x = circlesCenter_X - pointOnCircle_X(slope);
        }else{
            pointOnCircle.x = circlesCenter_X + pointOnCircle_X(slope);
        }
        pointOnCircle.y = slope * (pointOnCircle.x - circlesCenter_X) + circlesCenter_Y;
    }
    firstPieceView.center = pointOnCircle;
}

此问题也适用于AndroidBlackberry等!