我试图复制这种效果,但是在基于图像大小管理滚动视图插图时遇到了问题。
很明显,代码只能使用在did select和didZoom中被调用的一个函数进行泛化,但是我试图使其工作。
这是我使用的代码:
带有约束的故事板
图像选择
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let asset = imageDataset[indexPath.item]
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.isSynchronous = false
options.deliveryMode = .highQualityFormat
options.resizeMode = .exact
let size = CGSize(width: CGFloat(asset.pixelHeight) , height: CGFloat(asset.pixelHeight))
imageManager.requestImage(for: asset, targetSize: size , contentMode: .aspectFit, options: options) { (image, _) in
print(self.scrollView.zoomScale)
self.imageView.image = image
self.resetToOriginalState()
if let image = self.imageView.image {
let ratioW = self.imageView.frame.width / image.size.width
let ratioH = self.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 * self.scrollView.zoomScale > self.imageView.frame.width ? (newWidth - self.imageView.frame.width) : (self.scrollView.frame.width - self.scrollView.contentSize.width))
let top = 0.5 * (newHeight * self.scrollView.zoomScale > self.imageView.frame.height ? (newHeight - self.imageView.frame.height) : (self.scrollView.frame.height - self.scrollView.contentSize.height))
self.scrollView.contentInset = UIEdgeInsets(top: top, left: left , bottom: top, right: left)
}else {
self.scrollView.contentInset = UIEdgeInsets.zero
}
if !self.isImageShown {
collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
}
}
}
ScrollView委托
func scrollViewDidZoom(_ scrollView: UIScrollView) {
print(scrollView.zoomScale)
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
var 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 = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
}
}else {
scrollView.contentInset = UIEdgeInsets.zero
}
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}