在捏合时,即使平移到不同位置,图像视图也会移回原始帧的原点

时间:2014-02-13 19:58:11

标签: ios ios7 uigesturerecognizer uipinchgesturerecognizer

  1. 当动作正在进行时,使用UIPinchGestureRecognizer缩放图像视图时,图像“尝试”保留在初始帧.origin。

  2. 即使在平移手势将图像移动到另一个位置后,也会立即将其移回初始位置。

  3. Apple's Touches示例应用程序的所有代码,用于演示手势。

  4. 下面是pinch的代码,我在github上推送了一个示例应用程序,演示了这种行为:https://github.com/atokubi/TestImageManipulation

    预先感谢您的协助。

    - (IBAction)scaleItem:(UIPinchGestureRecognizer *)gestureRecognizer {
        [self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
        if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
            [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
            [gestureRecognizer setScale:1];
        }    
    } 
    
    - (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
            UIView *piece = gestureRecognizer.view;
            CGPoint locationInView = [gestureRecognizer locationInView:piece];
            CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];       
            piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
            piece.center = locationInSuperview;
        }
    }
    

1 个答案:

答案 0 :(得分:1)

如果要正确重新居中图像,可以使用以下方法:

// To re-center the image after zooming in and zooming out
- (void)centerViewContents
 {
   CGSize boundsSize = self.bounds.size;
   CGRect contentsFrame = self.imageView.frame;

   if (contentsFrame.size.width < boundsSize.width)
   {
      contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
   }
   else
   {
   contentsFrame.origin.x = 0.0f;
   }

   if (contentsFrame.size.height < boundsSize.height)
   {
     contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
   }
   else
   {
    contentsFrame.origin.y = 0.0f;
   }

   self.imageView.frame = contentsFrame;
}

在“adjustAnchorPointForGestureRecognizer”中添加此方法,如下所示:

  - (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
   {
     if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
     UIView *piece = gestureRecognizer.view;
     CGPoint locationInView = [gestureRecognizer locationInView:piece];
     CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];

     piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
     piece.center = locationInSuperview;
     [self centerViewContents];
     }
  }

我下载了你的代码并实现了它。它有效。

如果有帮助,请告诉我。