首先,在 viewDidLoad 添加设置:
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 10.0
实现方法一:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateMinZoomScaleForSize(view.bounds.size)
}
func updateMinZoomScaleForSize(_ size: CGSize) {
let widthScale = size.width / image.bounds.width
let heightScale = size.height / image.bounds.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.zoomScale = minScale
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return image
}
// 1 The scroll view calls scrollViewDidZoom(_:) each time the user zooms. In response, you simply call updateConstraintsForSize(_:) and pass in the view’s bounds size.
func scrollViewDidZoom(_ scrollView: UIScrollView) {
updateConstraintsForSize(view.bounds.size)
}
// 2 updateConstraintsForSize(_:) gets around an annoyance with UIScrollView: If the scroll view’s content size is smaller than its bounds, it places the contents at the top-left of the screen, rather than the center.
func updateConstraintsForSize(_ size: CGSize) {
// 3 You center the image vertically by subtracting the height of imageView from the view‘s height and dividing the result in half. This value adds padding to the top and bottom imageView constraints.
let yOffset = max(0, (size.height - image.frame.height) / 2)
imageViewTopConstraint.constant = yOffset
imageViewBottomConstraint.constant = yOffset
// 4 Similarly, you calculate an offset for the leading and trailing constraints of imageView, based on the width of the view.
let xOffset = max(0, (size.width - image.frame.width) / 2)
imageViewLeadingConstraint.constant = xOffset
imageViewTrailingConstraint.constant = xOffset
view.layoutIfNeeded()
}
实现方法二:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// 有点烧脑
if scrollView.zoomScale > 1 {
if let image = imageView.image {
let rationW = imageView.frame.width / image.size.width
let rationH = imageView.frame.height / image.size.height
let ratio = rationW < rationH ? rationW : rationH
let newWidth = image.size.width * ratio
let newHeight = image.size.height * ratio
let conditionLeft = newWidth*scrollView.zoomScale > imageView.frame.width
let left = 0.5 * (conditionLeft ? newWidth - imageView.frame.width : (scrollView.frame.width - scrollView.contentSize.width))
let conditionTop = newHeight*scrollView.zoomScale > imageView.frame.height
let top = 0.5 * (conditionTop ? newHeight - imageView.frame.height : (scrollView.frame.height - scrollView.contentSize.height))
scrollView.contentInset = UIEdgeInsets(top:top, left:left, bottom:top, right:left)
}else{
scrollView.contentInset = .zero
}
}
}
真机调试,对比证明,第二种实现方式更好一些。
参考:
网友评论