Scrollview内的图像与手势

时间:2017-12-12 07:02:20

标签: ios swift3 uiscrollview frameworks uiimageview

我有一个控制我制作包括在滚动视图中有一个图像,我应用了很多手势,特别是缩放(捏)。问题是,我希望scrollView的内容大小与图像新大小匹配,而不会影响:

  • 图像中心当前位置
  • 尺寸
  • 我可以滚动查看所有图像边界,没有多余的空间。

如果有任何不清楚的地方,请告诉我。

1 个答案:

答案 0 :(得分:1)

你应该这样做:

<强> Swift3:

import UIKit

class ViewController: UIViewController,UIScrollViewDelegate
{
    @IBOutlet weak var ScrollView: UIScrollView!
    @IBOutlet weak var ScrollImgView: UIImageView!

override func viewDidLoad()
{
    super.viewDidLoad()

    self.ScrollView.minimumZoomScale = 0.1
    self.ScrollView.maximumZoomScale = 5.0
    ScrollView.isUserInteractionEnabled = true
}
func viewForZooming(in scrollView: UIScrollView) -> UIView?
{
    return self.ScrollImgView
}
func scrollViewDidZoom(_ scrollView: UIScrollView)
{
    let imgViewSize:CGSize! = self.ScrollImgView.frame.size;
    let imageSize:CGSize! = self.ScrollImgView.image?.size;

    var realImgSize : CGSize;
    if(imageSize.width / imageSize.height > imgViewSize.width / imgViewSize.height)
    {
        realImgSize = CGSize(width: imgViewSize.width,height: imgViewSize.width / imageSize.width * imageSize.height);
    }
    else
    {
        realImgSize = CGSize(width: imgViewSize.height / imageSize.height * imageSize.width, height: imgViewSize.height);
    }
    var fr:CGRect = CGRect.zero
    fr.size = realImgSize;
    self.ScrollImgView.frame = fr;

    let scrSize:CGSize = scrollView.frame.size;
    let offx:CGFloat = (scrSize.width > realImgSize.width ? (scrSize.width - realImgSize.width) / 2 : 0);
    let offy:CGFloat = (scrSize.height > realImgSize.height ? (scrSize.height - realImgSize.height) / 2 : 0);
    scrollView.contentInset = UIEdgeInsetsMake(offy, offx, offy, offx);

    let scrollViewSize:CGSize = self.scrollViewVisibleSize();

    var imageCenter:CGPoint = CGPoint(x: self.ScrollView.contentSize.width/2.0, y:
        self.ScrollView.contentSize.height/2.0);

    let scrollViewCenter:CGPoint = self.scrollViewCenter()

    if (self.ScrollView.contentSize.width < scrollViewSize.width)
    {
        imageCenter.x = scrollViewCenter.x;
    }

    if (self.ScrollView.contentSize.height < scrollViewSize.height)
    {
        imageCenter.y = scrollViewCenter.y;
    }

    self.ScrollImgView.center = imageCenter;
}
func scrollViewCenter() -> CGPoint
{
    let scrollViewSize:CGSize = self.scrollViewVisibleSize()
    return CGPoint(x: scrollViewSize.width/2.0, y: scrollViewSize.height/2.0);
}
func scrollViewVisibleSize() -> CGSize
{
    let contentInset:UIEdgeInsets = self.ScrollView.contentInset;
    let scrollViewSize:CGSize = self.ScrollView.bounds.standardized.size;
    let width:CGFloat = scrollViewSize.width - contentInset.left - contentInset.right;
    let height:CGFloat = scrollViewSize.height - contentInset.top - contentInset.bottom;
    return CGSize(width:width, height:height);
}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()
}
}