Resize UIImageView based on UIIm

2023-02-21  本文已影响0人  VervertomJC

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?

上一篇下一篇

猜你喜欢

热点阅读