美文网首页
iOS 可以放大、缩小、滑动的imageView

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

作者: 黑暗森林的歌者 | 来源:发表于2016-08-09 10:54 被阅读1983次
    //底部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);
    }
    

    相关文章

      网友评论

          本文标题:iOS 可以放大、缩小、滑动的imageView

          本文链接:https://www.haomeiwen.com/subject/loxdsttx.html