简体   繁体   English

如何调整 UIView 中的图像大小?

[英]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 但在我看来我无法调整它的大小我得到了这样的东西:

UIview 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.您需要给 imageView 一个框架或使用 Autolayout 为 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 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.如果您发现程序化 AutoLayout 太具有挑战性,我建议您先从 Storyboards 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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