2017-02-28 51 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

我希望這可以幫助你