UIPinchGestureRecognizer定位两个手指之间的夹紧视图
我成功实现了捏放大的视图。 但是,这个观点并不是我所希望的。 对于使用iPad的电子书阅读器,我希望我的视图能够像iPad Photos.app一样居中alignment:当您捏和放大相册时,照片呈现在正在扩展的视图中。 该视图大致以第一手指上的右上angular和另一手指上的左下手指为中心。 我把它和一个泛识别器混合在一起,但是这样用户总是要捏,然后平移来调整。
这里是如此graphics的解释,我可以发布我的应用程序的video,如果这不清楚(没有秘密,我试图重现iPad的Photos.app …)
所以对于手指的初始位置,开始缩放:
这是现在的实际“缩放”框架。 广场更大,但位置在手指下方
这是我想要的:相同的大小,但不同origin.x和y:
(抱歉,我可怜的Photoshop技巧^^)
您可以通过方法handlingPinchGesture
的以下代码获取两个手指之间中点的CGPoint
。
CGPoint point = [sender locationInView:self];
下面是我的整个handlePinchGesture
方法。
/* instance variables CGFloat lastScale; CGPoint lastPoint; */ - (void)handlePinchGesture:(UIPinchGestureRecognizer *)sender { if ([sender numberOfTouches] < 2) return; if (sender.state == UIGestureRecognizerStateBegan) { lastScale = 1.0; lastPoint = [sender locationInView:self]; } // Scale CGFloat scale = 1.0 - (lastScale - sender.scale); [self.layer setAffineTransform: CGAffineTransformScale([self.layer affineTransform], scale, scale)]; lastScale = sender.scale; // Translate CGPoint point = [sender locationInView:self]; [self.layer setAffineTransform: CGAffineTransformTranslate([self.layer affineTransform], point.x - lastPoint.x, point.y - lastPoint.y)]; lastPoint = [sender locationInView:self]; }
看看Touches示例项目 。 具体来说这些方法可以帮助您:
// scale and rotation transforms are applied relative to the layer's anchor point // this method moves a gesture recognizer's view's anchor point between the user's fingers - (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; } } // scale the piece by the current scale // reset the gesture recognizer's rotation to 0 after applying so the next callback is a delta from the current scale - (void)scalePiece:(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]; } }