Swift基础之两指拉动图片变大变小

我们在使用APP的时候,有时会发现有些图片可以通过两指进行放大、缩小,今天就实现这样的一种效果,比较简单,不喜勿喷。。。。

var imageVi:UIImageView! = nil
    var myScrollV:UIScrollView! = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        imageVi = UIImageView.init(image: UIImage.init(named: "liwu.jpg"))
        setUpScrollView()
        myScrollV.delegate = self
        setZoomScaleFor(srollViewSize: myScrollV.bounds.size)
        myScrollV.zoomScale = myScrollV.minimumZoomScale
        recenterImage()
        
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        setZoomScaleFor(srollViewSize: myScrollV.bounds.size)
        
        if myScrollV.zoomScale < myScrollV.minimumZoomScale {
            myScrollV.zoomScale = myScrollV.minimumZoomScale
        }
        
        recenterImage()
    }
    private func recenterImage() {
        
        let scrollViewSize = myScrollV.bounds.size
        let imageViewSize = imageVi.frame.size
        let horizontalSpace = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2.0 : 0
        let verticalSpace = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.width) / 2.0 :0
        
        myScrollV.contentInset = UIEdgeInsetsMake(verticalSpace, horizontalSpace, verticalSpace, horizontalSpace)
        
    }
    private func setZoomScaleFor(srollViewSize: CGSize) {
        
        let imageSize = imageVi.bounds.size
        let widthScale = srollViewSize.width / imageSize.width
        let heightScale = srollViewSize.height / imageSize.height
        let minimunScale = min(widthScale, heightScale)
        
        myScrollV.minimumZoomScale = minimunScale
        myScrollV.maximumZoomScale = 3.0
        
    }
    private func setUpScrollView() {
        
        myScrollV = UIScrollView(frame: view.bounds)
        myScrollV.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        myScrollV.backgroundColor = UIColor.clear
        myScrollV.contentSize = imageVi.bounds.size
        myScrollV.addSubview(imageVi)
        self.view.addSubview(myScrollV)
        
    }
    //MARK:---------UIScrollViewDelegate
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageVi
    }
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        self.recenterImage()
    }

效果图:(源码下载:https://github.com/hbblzjy/SwiftBigAndSmallDemo)

Swift基础之两指拉动图片变大变小_第1张图片




你可能感兴趣的:(Swift开发知识,Swift语言基础学习到开发)