简体   繁体   中英

How to resize image in UIView?

I tried to set image into UIView but I can't resize it in my view I got something like this:

UIview

     let imageName = "rectanguloAzul"
     let image = UIImage(named: imageName)
     let imageView = UIImageView(image: image!)
     imageView.contentMode = .scaleAspectFill
     self.view.addSubview(imageView)

Welcome. You need to either give the imageView a frame or use Autolayout to set a layout for the image inside the UIView.

so either add this at the end:

imageView.frame = view.frame

But this will not be dynamic and you should learn how to keep updating the frame whenever the superview's frame changes.

Or you can add this, instead:

imageView.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
            imageView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
        ]
NSLayoutConstraint.activate(constraints)

Anyway, I really recommend you read up about AutoLayout a bit before you continue: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html https://www.raywenderlich.com/811496-auto-layout-tutorial-in-ios-getting-started

If you find programmatic AutoLayout to be too challenging, I would recommend possibly starting with Storyboards first.

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