Stephen Mather
Stephen Mather

Reputation: 275

UIImage in UIScrollView loads zoomed, rather than aspect fit

I am using Xcode 6.4 and writing in swift.

Right now I am trying to display a simple image in aspect fit and then be able to zoom in. Unfortunately the image loads fully zoomed. Everything else works just fine, double tapping even results in seeing the image aspect fit. How could I change my code so that the image loads in aspect fit?

My case is very similar to

UIImage Is Not Fitting In UIScrollView At Start

However, the objective-c answer no longer works.

Here is my code for viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    imageView = UIImageView(image: UIImage(named: "image.png"))

    scrollView = UIScrollView(frame: view.bounds)
    scrollView.backgroundColor = UIColor.blackColor()
    scrollView.contentSize = imageView.bounds.size
    scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    scrollView.contentOffset = CGPoint(x: 1000, y: 450)

    scrollView.addSubview(imageView)
    view.addSubview(scrollView)

    scrollView.delegate = self

    setZoomScale()
    setupGestureRecognizer()
}

And here is my code for setZoomScale()

    func setZoomScale() {
    let imageViewSize = imageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = min(widthScale, heightScale)
    scrollView.zoomScale = 1.0
}

All this originates from the online tutorial,

http://www.appcoda.com/uiscrollview-introduction/

Thank you in advance!

Upvotes: 3

Views: 2862

Answers (2)

Casey Perkins
Casey Perkins

Reputation: 1932

I tried the code in Stephen Mather's answer, but it did not work until I added this UIScrollView delegate method:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}

Upvotes: 1

Stephen Mather
Stephen Mather

Reputation: 275

Solution, in my setZoomScale function, I set the scrollView's zoomscale to "1.0" rather than the minimum

here is the corrected code, hope this helps someone!

func setZoomScale() {
    let imageViewSize = imageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    let minZoomScale = min(widthScale, heightScale)
    scrollView.minimumZoomScale = minZoomScale
    scrollView.zoomScale = minZoomScale
}

Upvotes: 5

Related Questions