简体   繁体   中英

Change size of UIImageView to fit different UIImages

So I have my UIImageView which is called imgView . Basically the user can add his own images to this view and save it again to his own gallery.

Because I don't know beforehand what the sizes the images from the User are the imgView should change it's size everytime to perfectly fit the image with aspectFit. If the image is small the imgView shrinks so it doesn't take up much space etc.

I have used this code in my viewDidLoad to achieve it but it doesn't do anything:

imgView.frame.size.width = imgView.image?.size.width
imgView.frame.size.height = imgView.image?.size.height

or

imgView.bounds.size = imgView.image?.size

What should I do differently?

Edit for alexburtnik's answer:

This is my code now:

In the Simulator:

在此处输入图片说明

I changed the background in my Image View to green. So right now it fills out the whole screen but it the view shouldn't be larger than the image itself.

Update width & height constraints:

I assume you're using autolayout. If so, you should change constraints' constant values instead of setting frames manually. Here is an example:

class ImageViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!    
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!

    func setImage(image: UIImage) {
        imageView.image = image
        let screenSize = UIScreen.main.bounds.size

        let imageAspectRatio = image.size.width / image.size.height
        let screenAspectRatio = screenSize.width / screenSize.height

        if imageAspectRatio > screenAspectRatio {
            widthConstraint.constant = min(image.size.width, screenSize.width)
            heightConstraint.constant = widthConstraint.constant / imageAspectRatio
        }
        else {
            heightConstraint.constant = min(image.size.height, screenSize.height)
            widthConstraint.constant = heightConstraint.constant * imageAspectRatio
        }
        view.layoutIfNeeded()
    }        
}

Note, that you also have to drag outlets for width and height constraints from storyboard to your viewController

Another solution without resizing UIImageView:

If other UI elements don't rely on UIImageView's frame and the only thing you care about is image appearance, you can just set content mode to Center or Top / Bottom / Right / Left etc:

在此处输入图片说明

Just set UIImageView's background to clear color

Just set the UIImageView Content Mode to Scale to Fit

缩放以适合

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM