Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

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

$
0
0

我们在使用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)





作者:hbblzjy 发表于2016/12/19 10:49:05 原文链接
阅读:98 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>