在ScrollView中使用pinch实现图片的缩放

 唉,为了使用pinch实现图片缩放在网上爬了两天,结果发现ScrollView类中就有一个pinchGestureRecognizer的属性:@property(nonatomic, readonly) UIPinchGestureRecognizer *pinchGestureRecognizer

所以只要将imageView放到ScrollView中,再经过一些基本设置,就可以使用pinch对图片进行缩放了!!

  基本设置包括:

  1.Scroll View的属性minimumZoomScalemaximumZoomScale,指明可缩放的程度

  2.Scroll view需遵守UIScrollViewDelegate协议,并实现viewForZoomingInScrollView:方法,该方法返回要被缩放的视图

  

  难怪苹果的官方文档中会这么写:A scroll view may need to zoom in response to touch events, such as double taps or other tap gestures, or in response to another user action other than a pinch gesture.看的时候还觉得挺奇怪:怎么把pinch专门列出来。。。


 一个最简单的实现例子:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIImage *image = [UIImage imageNamed:@"flower.png"];
    
    self.imageView.image = image;
    [self.imageView sizeToFit];//sizeToFit:调整reciver的size以适应子视图
    
    self.scrollView.contentSize = image.size;
    self.scrollView.delegate = self;
    self.scrollView.minimumZoomScale = 1.0;
    self.scrollView.maximumZoomScale = 10.0;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



你可能感兴趣的:(iOS开发)