Swift scaleAspectFit只有图像的高度

时间:2017-02-28 18:29:18

标签: ios swift

我的Swift代码中有这个imageview

let background_image: UIImageView = {
    let im = #imageLiteral(resourceName: "backg")
    let view=UIImageView()
    view.contentMode = .scaleAspectFit
    view.image=im
    return view
}()

我的background_image的尺寸是300x300,但我不知道im的大小。我希望im的宽度始终为300,但我不想缩小高度,我只想显示适合UIImageView的300px

1 个答案:

答案 0 :(得分:0)

您需要使用宽高比,并使用已知宽度300,您还需要将UIImageView内容模式设置为aspectFit

此代码示例使用SDWebImage进行图片加载,但您可以使用任何其他

self.newsImageView.sd_setImage(with: URL as URL, placeholderImage: UIImage(named: "genericImageR"), options: SDWebImageOptions(), completed: { (image, error, type, url) in
            DispatchQueue.global().async {
                DispatchQueue.main.async {
                    if(image != nil)
                    {
                        //your downloaded image aspect ratio
                        let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width
                        self.newsImageView.image = image
                        if(self.imageWasLoaded != nil)
                        {
                            //your know width 300, but if you want you can use the width of your component
                            self.imageWasLoaded!(self.newsImageView.frame.size.width * aspectRatio)
                        }
                    }
                }
            }
        })

并使用300 * aspectRatio

的高度结果调整您的UI

我希望这有助于你