项目中需要查看用户头像,类似微信客户端,如图所示:
创建UIScrollView和UIImageView
- (void)addSubviews
{
scrollview = [[UIScrollView alloc]initWithFrame:self.bounds];
scrollview.delegate = self;
scrollview.minimumZoomScale = 1;
scrollview.maximumZoomScale = 20;
scrollview.bounces = false;
scrollview.zoomScale = 1;
[self addSubview:scrollview];
_imageView = [[UIImageView alloc]init];
_imageView.contentMode = UIViewContentModeScaleToFill;
[scrollview addSubview:_imageView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gesture_dismissView)];
tap.numberOfTapsRequired = 1;
tap.cancelsTouchesInView = false;
[scrollview addGestureRecognizer:tap];
}
-(void)gesture_dismissView{
if (self.block_dismiss) {
self.block_dismiss(self);
}
}
-(void)layoutSubviews
{
[super layoutSubviews];
scrollview.frame = self.bounds;
CGFloat width = CGRectGetWidth(self.bounds) >= CGRectGetHeight(self.bounds)?CGRectGetHeight(self.bounds):CGRectGetWidth(self.bounds);
_imageView.frame = CGRectMake(CGRectGetMidX(scrollview.bounds) - width/2,CGRectGetMidY(scrollview.bounds) - width/2, width, width);
}
代理方法,让图像居中显示
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
//确保图像在屏幕中心
CGFloat xcenter = scrollView.center.x;
CGFloat ycenter = scrollView.center.y;
xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter;
ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter;
[_imageView setCenter:CGPointMake(xcenter, ycenter)];
}