如何动画旋转和移动UIView到其原始位置?

时间:2016-01-15 07:39:48

标签: ios objective-c animation

我有一个带有平移手势识别器的UIImageView,我根据用户操作移动和旋转。 当用户抬起手指时,我希望将其动画回原位,这是我的代码:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        startX = recognizer.view.center.x;
        startY = recognizer.view.center.y;
        startRotation = atan2(recognizer.view.transform.b, recognizer.view.transform.a);
        NSLog(@"Start Position %f %f %f", startX, startY, startRotation);
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {

        float distance = (startX - recognizer.view.center.x) / DISTANCE_TO_ACCEPT;
        CGPoint center = recognizer.view.center;


            // animate back
            [UIView animateWithDuration:0.5 animations:^{
                NSLog(@"Position %f %f %f", recognizer.view.center.x, recognizer.view.center.y, atan2(recognizer.view.transform.b, recognizer.view.transform.a));
                NSLog(@"Destination %f %f %f", startX, startY, startRotation);
                NSLog(@"Translation %f %f %f", startX - center.x, startY - center.y, (startRotation - atan2(recognizer.view.transform.b, recognizer.view.transform.a)));

                recognizer.view.transform = CGAffineTransformRotate(CGAffineTransformTranslate(recognizer.view.transform, startX - center.x, startY - center.y), (CGFloat) (startRotation - atan2(recognizer.view.transform.b, recognizer.view.transform.a)));
            }];


    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        // move image
        CGPoint translation = [recognizer translationInView:self.view];
        recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
        [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

        // rotate image
        float distance = (startX - recognizer.view.center.x) / DISTANCE_TO_ACCEPT;

        // cap distance
        if (distance > 1) {
            distance = 1;
        } else if (distance < -1) {
            distance = -1;
        }

        double rotation = 15 - startRotation;
        rotation = rotation * distance;
        recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, (CGFloat) ((rotation * M_PI / 180) - atan2(recognizer.view.transform.b, recognizer.view.transform.a)));

    }

}

但它永远不会到原来的位置。它总是有某种偏移。图像视图的进一步移动只会使情况变得更糟。 看起来在后向动画期间不会修改位置,因为当我再次平移图像时,开始位置和旋转等于前一次移动结束时的位置和旋转[即使屏幕上的图像位置和轮换已经改变]。

我在这里做错了什么?

由于

1 个答案:

答案 0 :(得分:3)

在UIGestureRecognizerStateEnded状态下尝试这样的事情:

recognizer.view.transform = CGAffineTransformIdentity;
recognizer.view.center = CGPointMake(startX,startY);