我在椭圆形的圆周上有一个椭圆形和一个视图。当您尝试拖动视图时,视图应仅在椭圆的圆周上移动。我怎样才能做到这一点? 任何样本方程都会有所帮助。感谢。
答案 0 :(得分:2)
CGPoint ovalCenter;
CGSize ovalSize;
- (CGPoint)constrainPointToOval:(CGPoint)point
{
float angle = atan2(point.y - ovalCenter.y, point.x - ovalCenter.x);
return CGPointMake(ovalSize.width * cosf(angle), ovalSize.height * sinf(angle));
}
您需要在其他位置设置ovalCenter
和ovalSize
。然后在设置视图位置之前运行触摸位置。
答案 1 :(得分:0)
我找到了一个解决方案,可以沿着正方形的两侧获得受约束的阻力。 如果有人可以改进代码,或者有更好的解决方案,那么非常欢迎。
- (CGPoint) constrainPointToSquare:(CGPoint) point
{
float pi = 3.14159265;
float s1,s2;
CGPoint squareDragPoint;
float squareSize = 200.0;
float angle;
angle = atan2 (point.y - mCenter.y, point.x - mCenter.x);
float x1 = point.x;
float x2 = mCenter.x;
float y1 = point.y;
float y2 = mCenter.y;
if (((3*(pi/4) <= angle && pi >= angle) || (-pi <= angle && -3*(pi/4) >= angle)))//left
{
s1 = y2 - squareSize;
s2 = x2 - squareSize * ((y1-y2)/(x1-x2));
squareDragPoint = CGPointMake(s1, s2);
}
else if (((-(pi/4) <= angle && 0.0 >= angle) || (0.0 <= angle && (pi/4) >= angle))) //right
{
s1 = y2 + squareSize;
s2 = x2 + squareSize * ((y1-y2)/(x1-x2));
squareDragPoint = CGPointMake(s1, s2);
}
else if (((-3*(pi/4) <= angle && -(pi/2) >= angle) || (-(pi/4) >= angle && -(pi/2) <= angle))) //top
{
s1 = x2 - squareSize;
s2 = y2 - squareSize * ((x1-x2)/(y1-y2));
squareDragPoint = CGPointMake(s2, s1);
}
else if (((3*(pi/4) >= angle && (pi/2) <= angle) || (pi/4 <= angle && (pi/2) >= angle))) //bottom
{
s1 = x2 + squareSize;
s2 = y2 + squareSize * ((x1-x2)/(y1-y2));
squareDragPoint = CGPointMake (s2, s1);
}
return squareDragPoint;
}