2016-04-15 111 views
1

我無法通過編程方式將圖像分配到UIImageView後獲取圖像的大小。在UIImageView中獲取圖像的大小

下面的代碼運行在一個循環中,並使用函數(getNoteImage)從URL(photoURL)下載圖像並將其分配給創建的UIImageView。我需要獲取圖像的高度,以便可以計算以下圖像和標籤的間距。

 var myImage :UIImageView 

     myImage = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)) 

     myImage.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, imageY) 

     myImage.getNoteImage(photoUrl) 

     self.detailsView.addSubview(myImage) 

     myImage.contentMode = UIViewContentMode.ScaleAspectFit 

     imageHeight = myImage.bounds.size.height 

我一直在使用

imageHeight = myImage.bounds.size.height 

,我理解爲在另一個職位的解決方案,但他只是返回屏幕尺寸的設備(667對iPhone6模擬器)嘗試。

任何人都可以指導我如何獲得正確的圖像大小? 謝謝

+2

一個UIImage有一個'size'屬性。你嘗試過使用它嗎?圖像視圖的大小應該是您設置的大小(=屏幕邊界)。下載圖像後,獲取其大小(使用'image.size')並使用它 – lostInTransit

回答

0

更改您的代碼,然後重試。只有你注意到強制設置UIImageView的框架,然後給它一個圖像,你可以使用「imageHeight = myImage.bounds.size.height」得到圖像的實際大小。

var myImage :UIImageView 
    //remove your initial frame parameters 
    myImage = UIImageView() 
    myImage.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, imageY) 
0

嘗試使用myImage.image.size.height並確保圖像從你應該把它寫在完成塊且僅當圖像被下載檢查該網址下載。 查看documentation瞭解更多詳情。

2

由於您的imageView佔據了整個屏幕,圖像的大小使用「寬高比適合」來獲得圖像顯示的高度,您將需要使用myImage.image!.size獲得原始圖像大小,然後根據myImage.bounds.size喜歡;

let imageViewHeight = myImage.bounds.height 
let imageViewWidth = myImage.bounds.width 
let imageSize = myImage.image!.size 
let scaledImageHeight = min(imageSize.height * (imageViewWidth/imageSize.width), imageViewHeight) 

這應該給圖像的實際高度,注意image.size使即其自然大小「圖像的邏輯尺寸」,而不是在其繪製的大小。

1

由於UIImage official doc

if let image = myImage.image { 
     let size = image.size 
     print("image size is \(size)") 
} else { 
    print("There is no image here..") 
} 

我想你的代碼同步圖像工作,我在你的問題理解,但如果不是我推薦使用AlamofireImage

隨着AlamofireImage你可以這樣做:

self.myImage.af_setImageWithURL(
    NSURL(string: photoUrl)!, 
    placeholderImage: nil, 
    filter: nil, 
    imageTransition: .CrossDissolve(0.5), 
    completion: { response in 
     print(response.result.value) # UIImage 
     if let image = response.result.value { 
      let size = image.size 
      print("image size is \(size)") 
     } 
     print(response.result.error) # NSError 
    } 
)