2013-04-27 45 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