UIScrollView Zooming & contentInset

前端 未结 3 1526
你的背包
你的背包 2021-01-31 10:39

Simliar to iOS Photos App where the user is zooming in and out of an image by pinching:

UIView > UIScrollView > UIImageView > UIImage

Initially, I had the issue

3条回答
  •  执笔经年
    2021-01-31 11:18

    Your approach looks correct. You need to update your code as below.

        func scrollViewDidZoom(scrollView: UIScrollView) {
    
        if scrollView.zoomScale > 1 {
    
            if let image = imageView.image {
    
                let ratioW = imageView.frame.width / image.size.width
                let ratioH = imageView.frame.height / image.size.height
    
                let ratio = ratioW < ratioH ? ratioW:ratioH
    
                let newWidth = image.size.width*ratio
                let newHeight = image.size.height*ratio
    
                let left = 0.5 * (newWidth * scrollView.zoomScale > imageView.frame.width ? (newWidth - imageView.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
                let top = 0.5 * (newHeight * scrollView.zoomScale > imageView.frame.height ? (newHeight - imageView.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))
    
                scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left)
            }
        } else {
            scrollView.contentInset = UIEdgeInsetsZero
        }
    }
    

提交回复
热议问题