0
votes

I want to apply these gestures on an imageview with following restrictions:

1)Double Tap: Zoom image two times and then return to original size

2)Pinch: Zoom image with a maximum limit and minimum limit to original size

3)Pan: When image is zoomed move image up/down only and image view should be bounded to its original bounds

I have tried the following code using tutorials but the pinch and pan do not work properly:

@IBAction func imgTapGesture(_ sender: UITapGestureRecognizer) {
    guard sender.view != nil else {return}
    if imgTapCount < 2 {
        let pinchCenter = CGPoint(x: sender.location(in: view).x - view.bounds.midX,
                                  y: sender.location(in: view).y - view.bounds.midY)
        let transform = sender.view?.transform.translatedBy(x: pinchCenter.x, y: pinchCenter.y)
            .scaledBy(x: 2, y: 2)
            .translatedBy(x: -pinchCenter.x, y: -pinchCenter.y)
        sender.view?.transform = transform!
    } else {
        UIView.animate(withDuration: 0.2, animations: {
            sender.view?.transform = CGAffineTransform.identity
        })
    }
    if imgTapCount < 2 {
        imgTapCount += 1
    } else {
        imgTapCount = 0
    }
}


@IBAction func imgPanGesture(_ sender: UIPanGestureRecognizer) {
    guard sender.view != nil else {return}
    let piece = sender.view!
    let translation = sender.translation(in: piece.superview)
    if sender.state == .began {
        self.initialCenter = piece.center
    }
    if sender.state != .cancelled {
        let newCenter = CGPoint(x: initialCenter.x + translation.x, y: initialCenter.y + translation.y)
        piece.center = newCenter
    }
    
    else {
        piece.center = initialCenter
    }
}

@IBAction func imgPinchGesture(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        if sender.scale < 1 && imgView.bounds.size == sender.view?.frame.size {
            sender.view?.transform = CGAffineTransform.identity
            return
        }
        switch sender.state {
        case .changed:
            isImgZoomed = true
            let pinchCenter = CGPoint(x: sender.location(in: view).x - view.bounds.midX,
                                      y: sender.location(in: view).y - view.bounds.midY)
            let transform = view.transform.translatedBy(x: pinchCenter.x, y: pinchCenter.y)
                .scaledBy(x: sender.scale, y: sender.scale)
                .translatedBy(x: -pinchCenter.x, y: -pinchCenter.y)
            
            view.transform = transform
            sender.scale = 1
        default:
            return
        }
    }
}

Please let me know what I am doing wrong.

@Vollan I have to zoom image two times and then return to original size . So I have used imgTapCount variable for that. I have already set number of taps of gesture to 2 on storyboardDiksha Rattan