2013-04-27 83 views
-4

我有UIView,我必須在圓形路徑中移動它。UIView在圓形路徑中移動(不是動畫)

enter image description here

+3

好知道... – 2013-04-27 18:04:30

+0

OK,現在你已經告訴我們想要做什麼,請更新您的問題以提出實際問題。你試過什麼了?你到底需要什麼幫助?請記住,你需要問一個具體的編程問題。 – rmaddy 2013-04-27 18:25:52

+0

...這個問題對我來說似乎沒問題... – samson 2013-04-27 19:24:13

回答

3

簡單。將UIImageView添加到UIView的子類,該子類具有圖像的屬性,以便您可以在代碼中移動它。實現touchesBegan:... touchesMoved:...和touchesEnded:...將圖像移動到圓上適當的點。這裏有一些簡單的數學:

編輯:添加了一些評論,並修復了象限錯誤。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    [super touchesMoved:touches withEvent:event]; 

    CGPoint viewCenter = CGPointMake(self.frame.size.width/2, self.frame.size.height/2); 
    CGPoint imageOrigin = self.imageOnCircle.frame.origin; 
    CGSize imageSize = self.imageOnCircle.frame.size; 
    CGPoint imageCenter = CGPointMake(imageOrigin.x + imageSize.width/2, 
             imageOrigin.y + imageSize.height/2); 

    CGFloat xDist = imageCenter.x - viewCenter.x; 
    CGFloat yDist = imageCenter.y - viewCenter.y; 
    CGFloat radius = sqrt(xDist*xDist + yDist*yDist); 

    CGPoint touchPoint = [[touches anyObject] locationInView:self]; 
    CGFloat touchXDist = touchPoint.x - viewCenter.x; 
    CGFloat touchYDist = touchPoint.y - viewCenter.y; 

    // angles in the view coordinates are measured from the positive x axis 
    // positive value means clockwise rotation 
    // -π/2 is vertically upward (towards the status bar) 
    // π/2 is vertically downward (towards the home button) 

    CGFloat newAngle = atanf(touchYDist/touchXDist); 
    // arctan takes a value between -π/2 and π/2 

    CGFloat newXDist = radius * cosf(newAngle); 
    // cos has a value between -1 and 1 
    // since the angle is between -π/2 and π/2, newXDist will always be positive. 
    if (touchXDist < 0) 
     newXDist *= -1; 

    CGFloat newYDist = radius * sinf(newAngle); 
    // sin has a value between -1 and 1 
    // since the angle is between -π/2 and π/2, newYDist can attain all its values. 
    // however, the sign will be flipped when x is negative. 
    if (touchXDist < 0) 
     newYDist *= -1; 

    CGPoint newCenter = CGPointMake(viewCenter.x + newXDist, 
            viewCenter.y + newYDist); 
    CGPoint newOrigin = CGPointMake(newCenter.x - self.imageOnCircle.frame.size.width/2, 
            newCenter.y - self.imageOnCircle.frame.size.height/2); 
    self.imageOnCircle.frame = CGRectMake(newOrigin.x, 
              newOrigin.y, 
              self.imageOnCircle.frame.size.width, 
              self.imageOnCircle.frame.size.height); 
} 

此外,您可能想添加一個最大/最小角度,以運動限制一方或另一方...

+0

謝謝。我的問題,我不明白如何計算新的職位與COS,罪... – Pavel 2013-04-27 18:50:50

+0

啊。查看[三維函數的wikipedia頁面](http://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent)。此外,要修復象限錯誤,只需將'newXDist'的符號設置爲與'touchXDist'的符號相同。 – samson 2013-04-27 19:27:04

+0

它現在效果更好,並且更具可讀性。 – samson 2013-04-27 20:31:58