Skip to content

Instantly share code, notes, and snippets.

@acrookston
Created January 14, 2015 19:12
Show Gist options
  • Save acrookston/9035ef8be9b5f07d9c4e to your computer and use it in GitHub Desktop.
Save acrookston/9035ef8be9b5f07d9c4e to your computer and use it in GitHub Desktop.
Swift image zoom
// The image is originally animated on to the view controller then added to the scroll view.
// So, there might be some animation residue in here.
// Class needs: <UIScrollViewDelegate>
func viewDidLoad() {
let width = UIScreen.mainScreen().bounds.size.width
let aspect: CGFloat = width / shotWidth
var frame = CGRectMake(0, 0, shotWidth * aspect, shotHeight * aspect)
self.scrollView = UIScrollView(frame: frame)
self.scrollView!.bounces = false
self.scrollView!.showsHorizontalScrollIndicator = false
self.scrollView!.showsVerticalScrollIndicator = false
self.scrollView!.userInteractionEnabled = true
self.scrollView!.delegate = self
self.scrollView!.bouncesZoom = false
self.scrollView!.scrollsToTop = false
self.scrollView!.maximumZoomScale = 2.0
self.scrollView!.minimumZoomScale = 1.0
self.doubleTap = UITapGestureRecognizer(target: self, action: "zoom:")
self.doubleTap!.numberOfTapsRequired = 2
self.doubleTap!.numberOfTouchesRequired = 1
self.scrollView!.addGestureRecognizer(self.doubleTap!)
// This was run when the animation is complete
self.imageView!.removeFromSuperview()
self.scrollView!.addSubview(self.imageView!)
self.addSubview(self.scrollView!)
}
func loadImage() {
// This is run in the callback when the full image has been loaded (image = UIImage)
self.imageView!.frame = CGRectMake(0, 0, image.size.width, image.size.height)
self.imageView!.image = image
self.scrollView!.contentSize = image.size
var imgwidth = CGFloat(self.bounds.size.width / image.size.width)
var imgheight = CGFloat(self.bounds.size.height / image.size.height)
var minZoom: CGFloat = min(imgwidth, imgheight)
NSLog("image size: %@ / %f", NSStringFromCGSize(image.size), minZoom)
if (minZoom <= 1) {
self.scrollView!.minimumZoomScale = minZoom
self.scrollView!.setZoomScale(minZoom, animated: false)
self.scrollView!.zoomScale = minZoom
}
}
// delegates:
func zoom(tapGesture: UITapGestureRecognizer) {
if (self.scrollView!.zoomScale == self.scrollView!.minimumZoomScale) {
var center = tapGesture.locationInView(self.scrollView!)
var size = self.imageView!.image!.size
var zoomRect = CGRectMake(center.x, center.y, (size.width / 2), (size.height / 2))
self.scrollView!.zoomToRect(zoomRect, animated: true)
} else {
self.scrollView!.setZoomScale(self.scrollView!.minimumZoomScale, animated: true)
}
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment