iOS 可以放大、缩小、滑动的imageView

//底部srollView
@property (nonatomic, strong) UIScrollView                    *imgScroll;
//显示图片
@property (nonatomic, strong) UIImageView                     *myImageView;
复制代码
-(UIScrollView *)imgScroll {
    if (!_imgScroll) {
        _imgScroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _imgScroll.delegate = self;
        //底部不要透明,否则图片缩小的时候会看到被遮住的界面
        _imgScroll.backgroundColor = [UIColor whiteColor];
        //最大级别
        _imgScroll.maximumZoomScale = 5;
        //初始化缩放级别
        self.imgScroll.zoomScale = 1;
        [self.view addSubview:_imgScroll];
    }
    return _imgScroll;
}
复制代码
-(UIImageView *)myImageView {
    if (!_myImageView) {
        _myImageView = [[UIImageView alloc] initWithFrame:self.imgScroll.bounds];
        _myImageView.backgroundColor = [UIColor clearColor];
        _myImageView.image = [UIImage imageNamed:@"123.png"];
        [self.imgScroll addSubview:_myImageView];
    }
    return _myImageView;
}
复制代码
- (void)openImage:(UIImage *)image {
     // 重置UIImageView的Frame,让图片居中显示
        self.myImageView.frame = CGRectMake(0, 0, self.imgScroll.width, self.imgScroll.width * image.size.height/image.size.width);
        [self scrollViewDidZoom:self.imgScroll];
        //设置scrollView的缩小比例
        CGSize maxSize = self.imgScroll.frame.size;
        CGFloat widthRatio = maxSize.width/localImage.size.width;
        CGFloat heightRatio = maxSize.height/localImage.size.height;
        CGFloat initialZoom = (widthRatio > heightRatio) ? heightRatio : widthRatio;
        self.imgScroll.minimumZoomScale = initialZoom;
复制代码
// 设置UIScrollView中要缩放的视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.myImageView;
}
复制代码
// 让UIImageView在UIScrollView缩放后居中显示
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    self.myImageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                            scrollView.contentSize.height * 0.5 + offsetY);
}
复制代码

转载于:https://juejin.im/post/5a93c93ef265da4e976eb341

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值