2017-02-28 54 views
-1

的高度我有这样的ImageView在我的银行代码斯威夫特scaleAspectFit只图像

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

background_image的尺寸是300×300,但我不知道。我im的大小要的im宽度总是是300,但我不想缩小高度,我只想显示适合在UIImageView中的300像素

+0

那是什么'scaleAspectFill'会假设高度大于宽度。 – dan

+0

@dan'scaleAspectFill'show last 300px,我怎样才能让它先显示300px? –

+0

听起来像你想'scaleAspectFit'而不是'scaleAspectFill'。你能为你的问题添加一个视觉例子吗? –

回答

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) 
         } 
        } 
       } 
      } 
     }) 

,并与的heigth结果调整自己的UI 300 *的aspectRatio

我希望这可以帮助你