[英]Getting size of an image in an 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
我在另一篇文章中將其作為解決方案來閱讀,但他只是返回設備的屏幕尺寸(iPhone6模擬器上為667)。
誰能指導我如何獲得正確的圖像尺寸? 謝謝
當您的imageView占據整個屏幕,並且使用“寬高比”調整圖像的大小以獲取圖像的顯示高度時,您需要使用myImage.image!.size
來獲取原始圖像大小,然后根據myImage.bounds.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
給出了“圖像的邏輯尺寸”,即其自然尺寸,而不是其繪制尺寸。
作為UIImage官方文檔 :
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
}
)
像這樣更改您的代碼,然后重試。 只有您注意到要強制設置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)
嘗試使用myImage.image.size.height
並確保從url下載了圖像,應將其寫在完成塊中,並且僅檢查是否已下載圖像。 有關更多詳細信息,請參見文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.