简体   繁体   中英

zoom image with scrollview swift ios

I have a problem with zooming an image with scroll view. If I put the scroll view on the left with width 125 and height 375, it does not zoom the image.

It only works if I put the scroll view on the center of the view.

Screenshot:

屏幕截图

Why is the scroll view not zooming when it's on the left side?

Here is my code

var imgview:UIImageView!

var imagepicked:UIImage!

var  minZoomScale:CGFloat!

let picker = UIImagePickerController()


@IBOutlet weak var scrollViewSquare: UIScrollView!

override func viewDidLoad() {

    super.viewDidLoad()
    picker.delegate = self
    scrollViewSquare.delegate = self
    picker.allowsEditing = false
    picker.sourceType = .PhotoLibrary
}

func imagePickerController(
    picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : AnyObject])
{
    imagepicked = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
        ImageViewInit()

    dismissViewControllerAnimated(false, completion: nil)
}

@IBAction func Pick(sender: AnyObject) {


    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){   
 self.presentViewController(picker, animated: true, completion: nil)
    }
}

func ImageViewInit(){
    imgview = UIImageView()
    imgview.frame =  CGRectMake(0, 0, imagepicked.size.width, imagepicked.size.height)
    imgview.image = imagepicked
    imgview.contentMode = .ScaleAspectFit
    imgview.backgroundColor = UIColor.greenColor()
    scrollViewSquare.maximumZoomScale = 4;
    scrollViewSquare.minimumZoomScale = 0.02;
    scrollViewSquare.bounces = true;
    scrollViewSquare.bouncesZoom = true;
    scrollViewSquare.contentMode = .ScaleAspectFit
    scrollViewSquare.contentSize = imagepicked.size
    scrollViewSquare.autoresizingMask = UIViewAutoresizing.FlexibleWidth
    scrollViewSquare.addSubview(imgview)
    setZoomScale()
}

func setZoomScale(){
    let imageViewSize = imgview.bounds.size
    let scrollViewSize = scrollViewSquare.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height
    minZoomScale = max(widthScale, heightScale)
    scrollViewSquare.minimumZoomScale = minZoomScale
    scrollViewSquare.zoomScale = minZoomScale
}


func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

        return imgview

}

Hello @Bensalem Ilyes,

I've tried your code and zooming does not work on simulator because the centre of pinch gesture is in the midle so pinch on scrollview is translated as simple pan gesture. I tried your code on real device and zooming works fine.

For repositioning pinch gesture on simulator: alt+shift key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM