从两个手指的中心放大UIImageView,也可以点击按钮

时间:2013-04-23 10:01:24

标签: ipad uipinchgesturerecognizer

我有一个图像视图,想要添加一些自定义捏手势识别器。我能够缩放我的图像视图,但问题是,它没有从两个手指的中心放大。

如何从两个手指的中心放大?这就是我目前正在做的事情(viewDidLoad

UIPinchGestureRecognizer* pinchRecognizer = 
    [[UIPinchGestureRecognizer alloc] initWithTarget:self
                                              action:@selector(handlePinch:)];    
 [imageView addGestureRecognizer:pinchRecognizer]; 

这是pinch方法的代码

- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{  

    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
    recognizer.scale = 1;

}

Thanx for rep guys ...现在我在这里更新我的问题.. 我想在按钮点击上缩放图像。我正在做的是

- (IBAction为)Zoom_image:(ID)发送方 {

 CGFloat scaleValue = 2;

 CGAffineTransform transform = GAffineTransformMakeScale(scaleValue,scaleValue);

 self.backgroundImgView.transform = transform;

}

2 个答案:

答案 0 :(得分:5)

这也有效。只需将图像移动到夹点的中心,将其缩放,然后在一次变换中返回其位置。

- (void) pinch:(UIPinchGestureRecognizer *) recognizer {

    CGPoint anchor = [recognizer locationInView:imageToScale];
    anchor = CGPointMake(anchor.x - imageToScale.bounds.size.width/2, anchor.y-imageToScale.bounds.size.height/2);

    CGAffineTransform affineMatrix = imageToScale.transform;
    affineMatrix = CGAffineTransformTranslate(affineMatrix, anchor.x, anchor.y);
    affineMatrix = CGAffineTransformScale(affineMatrix, [recognizer scale], [recognizer scale]);
    affineMatrix = CGAffineTransformTranslate(affineMatrix, -anchor.x, -anchor.y);
    imageToScale.transform = affineMatrix;

    [recognizer setScale:1];
}

答案 1 :(得分:0)

问题在于您所做的只是缩放视图。

您不会尝试将缩放转换为以两个手指点的中心为中心。

所以抓住两个手指点。找出他们的中心并添加翻译。

请注意,下面的代码将原则上显示 您需要做什么,我可以保证它将需要修复,因为在实践中仿射变换不是微不足道的,我不是你的错误修复程序。

- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
    UIView *view = recognizer.view;

    CGRect frame = view.bounds;

    //you may wish to get more accurate by querying and calculating against the touches via 
    //- (NSUInteger)numberOfTouches;
    //- (CGPoint)locationOfTouch:(NSUInteger)touchIndex inView:(UIView*)view;
    CGPoint nominalCenter = [recognizer locationInView:view];

    CGFloat deltaFromCenterX = CGRectGetMidX(frame) - nominalCenter.x;

    CGFloat deltaFromCenterY = CGRectGetMidY(frame) - nominalCenter.y;

    currentScale = currentScale * recognizer.scale;

    CGAffineTransform scale = CGAffineTransformMakeScale(currentScale, currentScale);

    CGAffineTransform translate = CGAffineTransformMakeTranslation(deltaFromCenterX, deltaFromCenterY);

    //possibly its going to be scale then translate instead
    CGAffineTransform final = CGAffineTransformConcat(translate, scale);

    recognizer.view.transform = final;
    recognizer.scale = 1;
}