-
-
Save paraches/ca58b5acb0585d5080feaaa5fa869998 to your computer and use it in GitHub Desktop.
UIImageView which can zoom by pinch and double tap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// pinchZoomImageVIewStudy | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var scrollView: UIScrollView! | |
@IBOutlet weak var imageView: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
scrollView.delegate = self | |
scrollView.minimumZoomScale = 1.0 | |
scrollView.maximumZoomScale = 4.0 | |
setupGesture() | |
if let image = UIImage(named: "myImage") { | |
imageView.image = image | |
} | |
} | |
} | |
extension ViewController: UIScrollViewDelegate { | |
func viewForZooming(in scrollView: UIScrollView) -> UIView? { | |
return imageView | |
} | |
} | |
extension ViewController { | |
func setupGesture() { | |
let recognizer = UITapGestureRecognizer(target: self, | |
action: #selector(onDoubleTap(_:))) | |
recognizer.numberOfTapsRequired = 2 | |
scrollView.addGestureRecognizer(recognizer) | |
} | |
@objc func onDoubleTap(_ sender: UITapGestureRecognizer) { | |
let scale = min(scrollView.zoomScale * 2, scrollView.maximumZoomScale) | |
if scale != scrollView.zoomScale { | |
let tapPoint = sender.location(in: imageView) | |
let size = CGSize(width: scrollView.frame.size.width / scale, | |
height: scrollView.frame.size.height / scale) | |
let origin = CGPoint(x: tapPoint.x - size.width / 2, | |
y: tapPoint.y - size.height / 2) | |
scrollView.zoom(to: CGRect(origin: origin, size: size), animated: true) | |
} | |
else { | |
scrollView.zoom(to: scrollView.frame, animated: true) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment