UIView在圆路径中移动(不是动画)

时间:2013-04-27 18:00:10

标签: ios

我有UIView,我必须在圆圈路径中移动它。

enter image description here

1 个答案:

答案 0 :(得分: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);
}

此外,您可能需要添加最大/最小角度,以限制移动到一侧或另一侧......