繁体   English   中英

在UIImageView中获取图像的大小

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM