美文网首页
Resize UIImageView based on UIIm

Resize UIImageView based on UIIm

作者: VervertomJC | 来源:发表于2023-02-21 09:19 被阅读0次

    Autolayout 根据图片宽高比例调整UIImageView尺寸

    override func viewDidLoad() {
            super.viewDidLoad()
    
            var image = UIImage(contentsOfFile: "yourFilePath")!
            var aspectR: CGFloat = 0.0
    
            aspectR = image.size.width/image.size.height
    
            imageView.translatesAutoresizingMaskIntoConstraints = false
            imageView.image = image
            imageView.contentMode = .scaleAspectFit
    
            NSLayoutConstraint.activate([
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            imageView.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor),
            imageView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor),
            imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1/aspectR)
            ])
    }
    
    

    The last 3 lines of NSLayoutConstraint.activate array ensures that the image width stays within the bounds of the container view and the height stays in proportion to width (i.e. the aspect ratio is maintained and height of imageView is shrunk to minimum required value).

    参考:How to resize UIImageView based on UIImage's size/ratio in Swift 3?

    相关文章

      网友评论

          本文标题:Resize UIImageView based on UIIm

          本文链接:https://www.haomeiwen.com/subject/icunkdtx.html