iOS开发基础-UIScrollView实现图片缩放

时间:2023-02-01 12:50:55

  当用户在 UIScrollView 上使用捏合手势时, UIScrollView 会给 UIScrollViewDelegate 协议发送一条消息,并调用代理的 viewForZoomingInScrollView: 方法,该方法返回的控件就是需要进行缩放的控件。

  实现缩放功能的步骤:

1)让控制器遵守 UIScrollView 的代理协议 UIScrollViewDelegate ;

2)为 UIScrollView 设置代理, _scrollView.delegate = self; ;

3)调用代理方法 viewForZoomingInScrollView: ,返回需要实现缩放功能的子控件;

4)设置缩放的范围, _scrollView.maximumZoomScale、_scrollView.minimumZoomScale 。

实例

  新建一个Single View Application,让 ViewController 类遵守 UIScrollViewDelegate 协议,并在类扩展中添加 UIScrollView 和 UIImageView 属性,如下:

1 //ViewController.m
2 @interface ViewController ()
3 {
4     UIScrollView *_scrollView;
5     UIImageView *_imageView;
6 }

  重载 viewDidLoad 方法如下:

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     //添加UIScrollView
 4     _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
 5     [self.view addSubview:_scrollView];
 6     
 7     //添加图片
 8     UIImage *image = [UIImage imageNamed:@"beauty4.jpg"];  9     //initWithImage:方法创建的_imageView的宽高和图片一样
10     _imageView = [[UIImageView alloc] initWithImage:image]; 11     [_scrollView addSubview:_imageView];
12     _scrollView.contentSize = image.size;
13     
14     //设置代理对象
15     _scrollView.delegate = self;
16     //设置最大缩小放大比例
17     _scrollView.maximumZoomScale = 2.0;
18     _scrollView.minimumZoomScale = 0.5;
19 }

  实现 viewForZoomingInScrollView: 方法,告诉 _scrollView  _imageView 是需要缩放的子控件:

1 //ViewController.m
2 - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
3     NSLog(@"实现图片的缩放");
4     return _imageView;
5 }

 


 

补充

  上述代码下划线部分,实例化 UIImageView 的方法可替换为:

1 _imageView = [[UIImageView alloc] init];
2 UIImage *image = [UIImage imageNamed:@"beauty4.jpg"];
3 _imageView.image = image;
4 _imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);

 

  跟缩放相关的其他代理方法:

 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view  缩放完毕的时候调用。

 - (void)scrollViewDidZoom:(UIScrollView *)scrollView  正在缩放的时候调用。

  在原代码之中添加如下代码:

1 - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
2     NSLog(@"%s", __FUNCTION__);
3 }
4 
5 - (void)scrollViewDidZoom:(UIScrollView *)scrollView {
6     NSLog(@"%s", __FUNCTION__);
7 }

 

  在真机上调试,使用捏合手势放大图片,输出如下:

1 2016-02-16 16:35:07.780 WJQScrollViewDemo[189:3549] -[ViewController viewForZoomingInScrollView:]
2 2016-02-16 16:35:07.781 WJQScrollViewDemo[189:3549] -[ViewController scrollViewWillBeginZooming:withView:]
3 2016-02-16 16:35:07.798 WJQScrollViewDemo[189:3549] -[ViewController scrollViewDidZoom:]

参考博客:iOS开发UI篇—UIScrollView控件实现图片缩放功能

代码下载:http://vdisk.weibo.com/s/DiY98QyXCNtD9