Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting size of an image in an UIImageView

I am having trouble getting the size of an image after it has been assigned to an UIImageView programmatically.

The code below runs in a loop and a function is used (getNoteImage) to download an image from an URL (photoURL) and assign it to the created UIImageView. I need to get the height of the image so that I can calculate the spacing for the following images and labels.

        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

I have tried using

imageHeight = myImage.bounds.size.height

which I read as a solution on another post but his just returns the screen size for the device (667 on the iPhone6 simulator).

Can anyone guide me on how I can get the correct image size ? Thanks

like image 429
Jarrow Avatar asked Oct 15 '25 14:10

Jarrow


2 Answers

As your imageView is taking up the whole screen and the image is sized using 'aspect fit' to get the height the image is displayed at you will need to get the original image size using myImage.image!.size then scale this based on myImage.bounds.size something like;

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

That should give the actual height of the image, note that image.size gives the "logical dimensions of the image" i.e. its natural size and not the size it is drawn at.

like image 116
sgib Avatar answered Oct 17 '25 06:10

sgib


As UIImage official doc:

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

I suppose your code working with synchronously image as I understand in your question, but if not I recommended to use AlamofireImage.

With AlamofireImage you can do:

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
    }
)
like image 31
Alessandro Ornano Avatar answered Oct 17 '25 08:10

Alessandro Ornano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!