美文网首页
UIScrollView实现图片缩放(二)

UIScrollView实现图片缩放(二)

作者: Maggie的小蜗居 | 来源:发表于2016-07-15 16:41 被阅读108次

    UIScrollView已经定义了捏合和移动的手势,正常的操作来说,还会使用双击图片进行缩放,这需要我们自己收动在UIScrollView加上点击的手势

    1.添加手势

            let doubleTapGesture = UITapGestureRecognizer(target: self,action: #selector(FLCameraFilterTopView.handleDoubleTap(_:)))
           doubleTapGesture.numberOfTapsRequired = 2
           scrollView.addGestureRecognizer(doubleTapGesture)
    

    2.处理点击手势

        func handleDoubleTap(tap:UITapGestureRecognizer) {
            
            //获取当前缩放值
            var newScale = scrollView.zoomScale
            
            if scrollView.zoomScale == 1 {
                newScale = 0.8
            }else {
                newScale = 1
            }
            
            //获取要缩放的大小和起始位置,这里都是居中
            let zoomRect = self.zoomRectForScale(newScale, center: CGPointMake(FL.ScreenWidth/2,FL.ScreenWidth/2))
    
            scrollView.zoomToRect(zoomRect, animated: true)
        }
        
        func zoomRectForScale(scale:CGFloat,center:CGPoint) -> CGRect {
            
            var zoomRect = CGRectZero
            
            zoomRect.size.height = scrollView.frame.size.height / scale
            zoomRect.size.width = scrollView.frame.size.width / scale
            zoomRect.origin.x = center.x - zoomRect.size.width/2.0
            zoomRect.origin.y = center.y - zoomRect.size.height/2.0
            
            return zoomRect
        }
    ```
    3. UIScrollViewDelegate 里设置
    
    ```
        func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
            //保证下一次的缩放在前次缩放的基础上
            scrollView.setZoomScale(scale, animated: true)
        }
        
    ```
    

    相关文章

      网友评论

          本文标题:UIScrollView实现图片缩放(二)

          本文链接:https://www.haomeiwen.com/subject/aodyjttx.html