UIPinchGestureRecognizer用于在xcode中缩放和平移图像

时间:2012-03-31 09:13:00

标签: iphone ios ipad

我创建了一个应用程序,其中有一个包含图像视图的视图。 下面的代码用于使用UIPinchGestureRecognizer缩放图像。 这里是我的观点的名称。

 - (void)viewDidLoad
    {
[super viewDidLoad];

//Zoom Photo
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[innerview addGestureRecognizer:pinchGesture];
[pinchGesture release];
mCurrentScale = 0;
mLastScale = 0;
}

-(void)handlePinch:(UIPinchGestureRecognizer*)sender {

NSLog(@"latscale = %f",mLastScale);

mCurrentScale += [sender scale] - mLastScale;
mLastScale = [sender scale];

if (sender.state == UIGestureRecognizerStateEnded)
{
    mLastScale = 1.0;
}

CGAffineTransform currentTransform = CGAffineTransformIdentity;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform,mCurrentScale, mCurrentScale);
innerview.transform = newTransform;

 } 

但如何在此使用ScrollView正确查看图像?

2 个答案:

答案 0 :(得分:2)

在滚动视图中嵌入您的innerView 完成捏合后,您可以获得新图像的大小,然后设置其内容大小

-(void)scale:(id)sender {
  if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
    lastScale = 1.0;
    CGSize zoomViewSize = CGSizeApplyAffineTransform(imgScrollView.frame.size, [(UIPinchGestureRecognizer *)sender view].transform);
    CGPoint centerPoint = CGPointApplyAffineTransform(imgScrollView.frame.origin, [(UIPinchGestureRecognizer *)sender view].transform);

    CGRect r = imgScrollView.bounds;
    CGSize scrollViewSize = imgScrollView.frame.size;
    imgScrollView.contentSize = zoomViewSize;
    imgScrollView.contentOffset = centerPoint; 
  }

  CGFloat currentScale = [[[(UIPinchGestureRecognizer*)sender view].layer valueForKeyPath:@"transform.scale"] floatValue];

  CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
  scale = MIN(scale, imgScrollView.maximumZoomScale / currentScale);   
  scale = MAX(scale, imgScrollView.minimumZoomScale / currentScale);
  CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
  CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
  [[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];
  lastScale = [(UIPinchGestureRecognizer*)sender scale];    
}

希望这可以帮到你:)

答案 1 :(得分:1)

试试这个

 -(void)scale:(id)sender {


    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        _lastScale = 1.0;
    }

    CGFloat scale = 1.0 - (_lastScale - [(UIPinchGestureRecognizer*)sender scale]);
    CGAffineTransform currentTransform = self.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

    [self setTransform:newTransform];


}