我的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
答案 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我希望这有助于你