嗨,所有聪明的人!我想为 iOS 应用程序创建一个触摸界面,允许用户在屏幕上拖动一个对象。然而,这个对象应该被限制为沿着一个圆的周长移动,这样如果用户试图将这个对象拖到那个路径之外,它就会粘在那个圆的最近点上。我做过一些 iPhone 编程,但我的数学很差。请帮忙!
问问题
173 次
1 回答
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;
}
这也可以类似地应用于Android
,Blackberry
等!
于 2012-08-28T09:44:25.700 回答