代码如下:
- (void)viewDidLoad
{
[super viewDidLoad];
//创建一个视图背景
_imageView = [[UIImageView alloc]initWithFrame:_scrollView.bounds];
_imageView.image = [UIImage imageNamed:@"p3.jpg"];
[_scrollView addSubview:_imageView];
//设置代理;
_scrollView.delegate = self;
//设置scrollView最大放大比例,之前的倍数,默认为1
_scrollView.maximumZoomScale = 2;
//设置scrollView最小缩小比例,之前的倍数,默认为1,0—1之间
_scrollView.minimumZoomScale = 0.5;
//缩放的反弹效果
//_scrollView.bouncesZoom = NO;
//上下左右预留的空间
//_scrollView.contentInset = UIEdgeInsetsMake(40, 40, 40, 40);
}
//设置scrollView所放的view,这个view必须是scrollView的子view
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imageView;
}
//scrollView缩放时调用
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
NSLog(@"缩放%f",scrollView.zoomScale);
// if (scrollView.zoomScale<1)
// {
// scrollView.frame = CGRectMake(scrollView.frame.size.width*(1-scrollView.zoomScale)/2, scrollView.frame.size.height*(1-scrollView.zoomScale)/2, scrollView.frame.size.width, scrollView.frame.size.height);
// }
// else
// {
// scrollView.frame = CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height);
// }
if (scrollView.zoomScale<1)
{
scrollView.contentInset=UIEdgeInsetsMake(scrollView.frame.size.height*(1-scrollView.zoomScale)/2, scrollView.frame.size.width*(1-scrollView.zoomScale)/2,0,0);
}
else
{
scrollView.contentInset = UIEdgeInsetsMake(0,0,0,0);
}
}
按住键盘上的option键,然后单击鼠标
效果图如下: