-4

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

在此处输入图像描述

4

1 回答 1

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

此外,您可能想要添加一个最大/最小角度,以将运动限制在一侧或另一侧......

于 2013-04-27T18:27:54.267 回答