UIImageView pinch zoom swift


Esperaba que alguien pudiera ayudarme. Estoy tratando de permitir que un usuario pellizque el zoom en un UIImageView (con un nivel máximo y mínimo permitido). Pero por alguna razón no funciona bien. La imagen se acerca un poco y luego rebota. Agradecer.

Aquí está el func zoom

func zoom(sender:UIPinchGestureRecognizer) {


    if sender.state == .Ended || sender.state == .Changed {

        let currentScale = self.view.frame.size.width / self.view.bounds.size.width
        var newScale = currentScale*sender.scale

        if newScale < 1 {
            newScale = 1
        }
        if newScale > 9 {
            newScale = 9
        }

        let transform = CGAffineTransformMakeScale(newScale, newScale)

        self.imageView?.transform = transform
        sender.scale = 1

    }

}
Author: RandomBytes, 2015-05-03

10 answers

Zoom de pellizco UIImageView con UIScrollView / / zoom de imagen ios en swift 3 y Xcode 8 letter URL del vídeo de Youtube

Establecer delegado uiscrollview en storyboard introduzca la descripción de la imagen aquí

 class PhotoDetailViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var imgPhoto: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()

        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 6.0        
        // scrollView.delegate = self - it is set on the storyboard.
    }  

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {

        return imgPhoto
    }
 76
Author: Parth Changela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-24 06:51:39

Decidí agregar ImageView a UIScrollView. Permite al usuario hacer zoom y panorámica. Aquí está el código que usé.

Para ajustar el zoom max/min utilicé:

    scrollImg.minimumZoomScale = 1.0
    scrollImg.maximumZoomScale = 10.0

Aquí está el resto del código.

    var vWidth = self.view.frame.width
    var vHeight = self.view.frame.height

    var scrollImg: UIScrollView = UIScrollView()
    scrollImg.delegate = self
    scrollImg.frame = CGRectMake(0, 0, vWidth!, 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

    defaultView!.addSubview(scrollImg)

    imageView!.layer.cornerRadius = 11.0
    imageView!.clipsToBounds = false
    scrollImg.addSubview(imageView!)

También tuve que añadir esto también

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return self.imageView
}

Prototipo de función Swift 3 & above

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return self.mainImage
}
 40
Author: RandomBytes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 15:14:19

En mi opinión, el problema es su determinación de la escala actual. Siempre es igual a 1, porque cambia la escala de su ImageView. Debe asignar su currentScale de la siguiente manera:

let currentScale = self.imageView?.frame.size.width / self.imageView?.bounds.size.width  
 6
Author: Andrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-03 14:02:42

La opción para swift 4

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var scrolView: UIScrollView!
@IBOutlet weak var imgPhoto: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()
    scrolView.delegate = self
    scrolView.minimumZoomScale = 1.0
    scrolView.maximumZoomScale = 10.0
  }

  func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imgPhoto
  }
}
 6
Author: Heretic Sic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 08:48:49

Puede usar ImageScrollView de código abierto, una vista de imagen con zoom y desplazable. http://github.com/huynguyencong/ImageScrollView

Al igual que este código abierto, agregue ImageView a ScrollView

open class ImageScrollView: UIScrollView {
   var zoomView: UIImageView? = nil
}

extension ImageScrollView: UIScrollViewDelegate{

    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return zoomView
    }

    public func scrollViewDidZoom(_ scrollView: UIScrollView) {
        adjustFrameToCenter()
    }
}
 5
Author: huync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-23 00:38:31

Solución Swift 3

Este es el código que usé. He añadido ImageView a ScrollView como un subview.

class ZoomViewController: UIViewController,UIScrollViewDelegate {

@IBOutlet weak var scrollView:UIScrollView!
@IBOutlet weak var imageView:UIImageView!

override func viewDidLoad() {

        super.viewDidLoad()
        scrollView.delegate = self

        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 10.0//maximum zoom scale you want
        scrollView.zoomScale = 1.0

}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
}
 3
Author: Tharanga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-24 10:30:10

Solución Swift 3

Por defecto UIImageView's userInteration está desactivado. Habilítelo antes de agregar cualquier gesto en UIImageView.

imgView.isUserInteractionEnabled = true

El factor de escala relativo a los puntos de los dos toques en la pantalla coordenadas

var lastScale:CGFloat!
func zoom(gesture:UIPinchGestureRecognizer) {
    if(gesture.state == .began) {
        // Reset the last scale, necessary if there are multiple objects with different scales
        lastScale = gesture.scale
    }
    if (gesture.state == .began || gesture.state == .changed) {
    let currentScale = gesture.view!.layer.value(forKeyPath:"transform.scale")! as! CGFloat
    // Constants to adjust the max/min values of zoom
    let kMaxScale:CGFloat = 2.0
    let kMinScale:CGFloat = 1.0
    var newScale = 1 -  (lastScale - gesture.scale)
    newScale = min(newScale, kMaxScale / currentScale)
    newScale = max(newScale, kMinScale / currentScale)
    let transform = (gesture.view?.transform)!.scaledBy(x: newScale, y: newScale);
    gesture.view?.transform = transform
    lastScale = gesture.scale  // Store the previous scale factor for the next pinch gesture call
  }
}
 3
Author: RajeshKumar R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-30 09:01:58

Creo que el mayor problema está al final de su func, usted tiene sender.scale = 1. Si eliminas esa línea de código, tu imagen no debería rebotar cada vez.

 0
Author: Logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 23:22:53

He publicado una respuesta aquí para la funcionalidad de zoom con pellizco y doble toque en Swift 3. Funciona perfectamente.

 0
Author: Akhilendra Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-10 17:26:27

Esta es una pregunta antigua, pero no veo ninguna respuesta que explique lo que está mal con el código original.

Esta línea:

let currentScale = self.view.frame.size.width / self.view.bounds.size.width

Está trabajando en la vista principal en lugar de la ImageView, por lo que el cálculo de la escala siempre es ~1

Este simple cambio hace que se comporte como se espera

let currentScale = sender.view!.frame.size.width / sender.view!.bounds.size.width

Cambiando self a sender (y forzando a view a desenvolver) el cálculo de la escala funciona como se esperaba.

 0
Author: Dean Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 07:51:56