ZoomImageView.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // ZoomImageView.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/11/7.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. class ZoomImageView: UIScrollView {
  10. override init(frame: CGRect) {
  11. super.init(frame: frame)
  12. self.setupView()
  13. }
  14. required init?(coder aDecoder: NSCoder) {
  15. super.init(coder: aDecoder)
  16. self.setupView()
  17. }
  18. var _imageView: UIImageView?
  19. func setupView() {
  20. self.delegate = self
  21. self.showsHorizontalScrollIndicator = false
  22. self.showsVerticalScrollIndicator = false
  23. //设置最大放大倍数
  24. self.minimumZoomScale = 1.0;
  25. self.maximumZoomScale = 2.0;
  26. //粘贴一张图片
  27. self._imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height))
  28. self._imageView!.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2);
  29. self._imageView!.contentMode = .scaleAspectFit;
  30. //添加双击事件
  31. let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
  32. doubleTapGesture.numberOfTapsRequired = 2
  33. self._imageView!.addGestureRecognizer(doubleTapGesture)
  34. self._imageView!.isUserInteractionEnabled = true
  35. self.addSubview(self._imageView!)
  36. }
  37. @objc private func handleDoubleTap(gesture: UIGestureRecognizer) {
  38. var zoomScale = self.zoomScale
  39. if zoomScale == 1.0 {
  40. zoomScale = 2.0
  41. }else {
  42. zoomScale = 1.0
  43. }
  44. let zoomRect = self.zoomRectForScale(scale: zoomScale, center: gesture.location(in: gesture.view))
  45. self.zoom(to: zoomRect, animated: true)
  46. }
  47. private func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect{
  48. let width = self.frame.size.width / scale
  49. let height = self.frame.size.height / scale
  50. return CGRect(x: center.x - (width / 2.0), y: center.y - (height / 2.0), width: width, height: height)
  51. }
  52. }
  53. extension ZoomImageView: UIScrollViewDelegate {
  54. }