用scrollview swift ios缩放图像

时间:2016-08-27 16:28:24

标签: ios swift uiscrollview image-zoom

我在使用滚动视图缩放图像时遇到问题。 如果我将滚动视图放在宽度为125和高度为375的左侧,则不会缩放图像。

仅当我将滚动视图放在视图的中心时才有效。

截图:

Screenshot

为什么滚动视图在左侧不会缩放?

这是我的代码

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

}

1 个答案:

答案 0 :(得分:0)

Hello @Bensalem Ilyes,

我已经尝试过您的代码并且缩放在模拟器上不起作用,因为捏合手势的中心位于midle中,因此将scrollview上的pinch翻译为简单的平移手势。我在真实设备上尝试了你的代码并且缩放工作正常。

用于在模拟器上重新定位捏合手势: alt + shift键