Francesco Piraneo G.
Francesco Piraneo G.

Reputation: 870

UIImageView: How to show scaled image?

I'm new to iOS app development and I begun to learn from this great tutorial:

Start Developing iOS Apps (Swift)

https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html#//apple_ref/doc/uid/TP40015214-CH6-SW1

Everything looks great but when trying to load an image from "Camera roll" on the simulator, I get the image shown oversized and filling all the iPhone simulator screen instead of just showing into the UIImageView box as shown on tutorial images.

The funny fact is that also downloading the correct project provided at the end of the lesson (see the bottom of the page) I get the same issue.

Googling around I get some ideas to insert a:

    // The info dictionary may contain multiple representations of the image. You want to use the original
    guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image
    photoImageView.image = selectedImage
    photoImageView.contentMode = UIViewContentMode.scaleAspectFit

    // Dismiss the picker
    dismiss(animated: true, completion: nil)

after loading image from the camera roll, but lead to no results...

I'm using Xcode 9.2 with deployment target 11.2 and iPhone 8 plus as a target for the simulator.

Any help is apreciated.

Upvotes: 0

Views: 111

Answers (1)

GustavoAzOl
GustavoAzOl

Reputation: 299

It happens because the sample code is only restricting the proportion of the UIImageView (the 1:1 constraint you added in storyboard). In this way, it will always keep your imageView squared but will not limit the size.

As the sample tells, you entered a placeholder size, that is only kept until you set some image on it. When you enter a new image on the UIImageView it changes to the size of the image you set (in your case, probably a bigger image for the camera roll). That's probably why its getting so large.

I think the easy way to fix this to add other constraints in storyboard to limit the size (like actually size or border constraints).

Upvotes: 2

Related Questions