此示例使用 UIScrollView 的常规缩放功能,其中包含 UIImageView 作为子视图。例如,您可以在 MWPhotoBrowser 库中找到这种缩放的实现。 _imageView、_doubleTapBeganPoint、_longPressBeganPoint、_minScale 是你的类(UIScrollView 子类)iVars。所以从初始化开始:
UILongPressGestureRecognizer* lpgs = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageLongPressed:)];
lpgs.minimumPressDuration = .2;
[self addGestureRecognizer:lpgs];
标准缩放处理程序:
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return _imageView;
}
使用 touchesBegan 捕捉双击(UITapGestureRecognizer 出于某种原因不想使用 UILongPressGestureRecognizer):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
NSUInteger tapCount = touch.tapCount;
switch (tapCount) {
case 2:
[self handleDoubleTapBegan:[touch locationInView:self.superview]];
break;
default:
break;
}
[[self nextResponder] touchesEnded:touches withEvent:event];
}
- (void)handleDoubleTapBegan:(CGPoint)touchPoint {
_doubleTapBeganPoint = touchPoint;
NSLog(@"image double tap began at location: %@", NSStringFromCGPoint(touchPoint));
}
处理长按并使用 Y 坐标的差异来计算缩放比例。 _minScale 存储您的初始缩放比例,以便我们恢复它。
- (void) imageLongPressed:(UIGestureRecognizer*)gesture {
if (gesture.state == UIGestureRecognizerStateBegan)
{
self.maximumZoomScale = _maxScale * 2;
self.minimumZoomScale = _minScale / 3;
_longPressBeganPoint = [gesture locationInView:self.superview];
[self setZoomScale:_minScale animated:YES];
NSLog(@"image long press began at location: %@", NSStringFromCGPoint(_longPressBeganPoint));
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
CGPoint p = [gesture locationInView:self.superview];
//NSLog(@"image long press changed at location: %@", NSStringFromCGPoint(p));
if (CGPointEqualToPoint(_longPressBeganPoint, _doubleTapBeganPoint))
{
_zoom = _minScale + (p.y - _longPressBeganPoint.y) / 100.0;
NSLog(@"zoom scale: %f", _zoom);
[self setZoomScale:_zoom animated:NO];
}
}
else if (gesture.state == UIGestureRecognizerStateEnded)
{
NSLog(@"image long press ended at location: %@", NSStringFromCGPoint([gesture locationInView:gesture.view]));
if (self.zoomScale < _minScale)
{
[self setZoomScale:_minScale animated:YES];
NSLog(@"min zoom scale: %f", _minScale);
}
}
}