2011-11-22 105 views

回答

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)); 
} 

你需要設置ovalCenterovalSize別處。然後在設置視圖位置之前通過此位置運行觸摸位置。

+0

美麗。你是數學家還是科學家? :) 謝謝 :)。 –

+0

您爲ovalSize分配相同的高度和寬度,並獲得一個圓形路徑。廣場呢? –

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; 
}