Search code examples
iosswiftswift2

Swift image does not fit in the scrollview


I have a scrollview which loads an image to zoom in and zoom out, the problem is that I want the image to be loaded full like this

http://www.capital.cl/wp-content/uploads/2015/04/avengers.jpg

so the user can see the complete image first

but it looks like this:

IosEmulator

this is the code

import UIKit

class Paso2: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var noCheckBox2: CheckBox!
    @IBOutlet weak var siCheckBox2: CheckBox!
   
    var imageView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        scrollView.delegate = self
        
        // imageView.contentMode = UIViewContentMode.ScaleAspectFill
        // imageView.clipsToBounds = true
        imageView.image = UIImage(named: "avengers.jpg")
        
        let imagee = UIImage(named: "avengers.jpg")
        let size = imagee?.size
        
        
        imageView.frame = CGRectMake(0, 0, size!.width, size!.height)
        imageView.contentMode = .Top
        scrollView.addSubview(imageView)
        
        scrollView.contentSize = size!
        let scrollViewFrame = scrollView.frame
        let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
        let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
        let minScale = min(scaleHeight, scaleWidth)
        
        scrollView.minimumZoomScale = 1
        scrollView.maximumZoomScale = 4
        scrollView.zoomScale = minScale
        
        centerScrollViewContents()
        
    }
    
    
    
    func centerScrollViewContents(){
        let boundsSize = scrollView.bounds.size
        var contentsFrame = imageView.frame
        
        if contentsFrame.size.width < boundsSize.width {
            contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2
        }
        else {
            contentsFrame.origin.x = 0
        }
        
        if contentsFrame.size.height < boundsSize.height {
            contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2
        }
        else {
            contentsFrame.origin.y = 0
        }
        
        imageView.frame = contentsFrame
        // scrollView.frame = contentsFrame
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        centerScrollViewContents()
    }
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }

Solution

  • Just change this.

            imageView.contentMode = .ScaleAspectFit
    

    without zoom

    enter image description here enter image description here

    with zoom