美文网首页
Swift UIScrollView图片缩放

Swift UIScrollView图片缩放

作者: 喵喵粉 | 来源:发表于2020-10-22 08:58 被阅读0次
    1. 布局
      UIScrollView上加UIImageView,拉好约束

    2. 图片比例缩放

    //拿到图片高度
    let hImage = kScreenW*image.size.height/image.size.width
    layoutIconH.constant = hImage
    
    1. 添加双击手势
    //2. 双击
    let dTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
    dTap.numberOfTapsRequired = 2
    ivIcon.addGestureRecognizer(dTap
    
    @objc fileprivate func handleDoubleTap(_ ges: UITapGestureRecognizer) {
        
        guard let vGes = ges.view else {
            return
        }
        
        let newScale = isScaled ? 1 : sv.zoomScale*1.5
        let zoomRect = zoomRectForScale(newScale, center: ges.location(in: vGes))
        
        isScaled = !isScaled
        
        sv.zoom(to: zoomRect, animated: true)
    }
    
    fileprivate func zoomRectForScale(_ scale: CGFloat, center: CGPoint) -> CGRect {
        var zoomRect = CGRect.zero
        zoomRect.size.height = sv.height/scale
        zoomRect.size.width = sv.width/scale
        
        zoomRect.origin.x = center.x-(zoomRect.width*0.5)
        zoomRect.origin.y = center.y-(zoomRect.height*0.5)
    
        return zoomRect
    }
    
    1. UIScrollView代理方法
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        scrollView.setZoomScale(scale, animated: false)
    }
    
    //返回要缩放的UIImageView
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return ivIcon
    }
    

    相关文章

      网友评论

          本文标题:Swift UIScrollView图片缩放

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