UIImageView pinch zoom swift

前端 未结 13 775
误落风尘
误落风尘 2020-11-28 04:06

I was hoping someone could help me out. I am trying to allow a user to pinch zoom on a UIImageView(with a max and min level allowed). But for some reason the it does not wor

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 04:43

    Swift 3 solution

    By default UIImageView's userInteration is disabled. Enable it before adding any gestures in UIImageView.

    imgView.isUserInteractionEnabled = true

    The scale factor relative to the points of the two touches in screen coordinates

    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
      }
    }
    

提交回复
热议问题