Get width of a resized image after UIViewContentModeScaleAspectFit

Sergey Grischyov picture Sergey Grischyov · Feb 1, 2013 · Viewed 17.3k times · Source

I have my UIImageView and I put an image into it that I resize like this:

UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)];
attachmentImageNew.image = actualImage;
attachmentImageNew.backgroundColor = [UIColor redColor];
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;

I tried getting the width of the resized picture in my UIImageView by doing this:

NSLog(@"Size of pic is %f", attachmentImageNew.image.size.width);

But it actually returns me the width of the original picture. Any ideas on how do I get the frame of the picture that I see on screen?

EDIT: Here's how my UIImageView looks, red area is its backgroundColor

enter image description here

Answer

Mikhail picture Mikhail · Feb 1, 2013

I don't know is there more clear solution, but this works:

float widthRatio = imageView.bounds.size.width / imageView.image.size.width;
float heightRatio = imageView.bounds.size.height / imageView.image.size.height;
float scale = MIN(widthRatio, heightRatio);
float imageWidth = scale * imageView.image.size.width;
float imageHeight = scale * imageView.image.size.height;