斯威夫特 3
通常,双击和捏合手势都需要图像缩放功能,因此我提供了完整的解决方案来实现相同的功能。双击缩放受上述答案的启发,捏缩放取自此处。
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var imageView: UIImageView!
var scrollImg: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let vWidth = self.view.frame.width
let vHeight = self.view.frame.height
scrollImg = UIScrollView()
scrollImg.delegate = self
scrollImg.frame = CGRect(x: 0, y: 0, width: vWidth, height: vHeight)
scrollImg.backgroundColor = UIColor(red: 90, green: 90, blue: 90, alpha: 0.90)
scrollImg.alwaysBounceVertical = false
scrollImg.alwaysBounceHorizontal = false
scrollImg.showsVerticalScrollIndicator = true
scrollImg.flashScrollIndicators()
scrollImg.minimumZoomScale = 1.0
scrollImg.maximumZoomScale = 10.0
let doubleTapGest = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapScrollView(recognizer:)))
doubleTapGest.numberOfTapsRequired = 2
scrollImg.addGestureRecognizer(doubleTapGest)
self.view.addSubview(scrollImg)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: vWidth, height: vHeight))
imageView.image = UIImage(named: "cat")
imageView!.layer.cornerRadius = 11.0
imageView!.clipsToBounds = false
scrollImg.addSubview(imageView!)
}
func handleDoubleTapScrollView(recognizer: UITapGestureRecognizer) {
if scrollImg.zoomScale == 1 {
scrollImg.zoom(to: zoomRectForScale(scale: scrollImg.maximumZoomScale, center: recognizer.location(in: recognizer.view)), animated: true)
} else {
scrollImg.setZoomScale(1, animated: true)
}
}
func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
zoomRect.size.height = imageView.frame.size.height / scale
zoomRect.size.width = imageView.frame.size.width / scale
let newCenter = imageView.convert(center, from: scrollImg)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
}