UIScrollView之Zoom

项目中需要查看用户头像,类似微信客户端,如图所示:
这里写图片描述

创建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)];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值