如何通过旋转移动uiview圆圈轨迹?

时间:2012-05-23 13:09:08

标签: iphone objective-c ios core-animation

就像图片中的路径

(新用户不允许发布图片,抱歉我只能提供链接)

http://cdn.dropmark.com/30180/3bd0f0fc6ee77c1b6f0e05e3ea14c821f8b48a82/questiong1-1.jpg

非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

在触摸事件委托时尝试此操作(如果要使用触摸事件旋转视图) -

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
    touches = [event allTouches];
    UITouch *touch = [[event allTouches] anyObject];

    CGPoint Pageposition = [touch locationInView:self];

    CGPoint prevPoint = [[[touches allObjects] objectAtIndex:0] previousLocationInView:self];
    CGPoint curPoint = [[[touches allObjects] objectAtIndex:0] locationInView:self];

    float prevAngle = atan2(prevPoint.x, prevPoint.y);
    float curAngle= atan2(curPoint.x, curPoint.y);
    float angleDifference = curAngle - prevAngle;

    CGAffineTransform newTransform3 = CGAffineTransformRotate(self.transform, angleDifference);
    self.transform = newTransform3;
  } 

使用变换旋转,并告诉我它是否有效..

答案 1 :(得分:2)

请查看my answer for this question关于“围绕任意点旋转标签”的更多详细说明,了解旋转时使用锚点的方法(忽略关键帧动画的答案,因为它们更复杂而不是“正确”这项工作的工具“即使答案是这样说的。”

简而言之:将定位点设置为点(在视图图层的单位坐标系中)到视图外的点,然后应用正常旋转动画。


编辑:要记住的一件事

使用位置,边界和锚点计算图层的框架(也是视图的框架)。更改anchorPoint将更改视图在屏幕上显示的位置。您可以通过在更改定位点后重新设置框架来对此进行计数(这将为您设置位置)。否则,您可以将位置设置为您自己旋转的点。 Layer Geometry and Transforms(在另一个问题中链接)也提到了这一点。


我在该答案中提供的代码(推广到UIView和Core Animation而不是UIView-animations):

#define DEGREES_TO_RADIANS(angle) (angle/180.0*M_PI)

- (void)rotateView:(UIView *)view 
       aroundPoint:(CGPoint)rotationPoint 
          duration:(NSTimeInterval)duration 
           degrees:(CGFloat)degrees {

    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    [rotationAnimation setDuration:duration];
    // Additional animation configurations here...

    // The anchor point is expressed in the unit coordinate
    // system ((0,0) to (1,1)) of the label. Therefore the 
    // x and y difference must be divided by the width and 
    // height of the view (divide x difference by width and 
    // y difference by height).
    CGPoint anchorPoint = CGPointMake((rotationPoint.x - CGRectGetMinX(view.frame))/CGRectGetWidth(view.bounds),
                                      (rotationPoint.y - CGRectGetMinY(view.frame))/CGRectGetHeight(view.bounds));

    [[view layer] setAnchorPoint:anchorPoint];
    [[view layer] setPosition:rotationPoint]; // change the position here to keep the frame
    CATransform3D rotationTransform = CATransform3DMakeRotation(DEGREES_TO_RADIANS(degrees), 0, 0, 1);
    [rotationAnimation setToValue:[NSValue valueWithCATransform3D:rotationTransform]];

    // Add the animation to the views layer
    [[view layer] addAnimation:rotationAnimation
                        forKey:@"rotateAroundAnchorPoint"]  
}