Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone : Getting the size of an image after AspectFt

Tags:

Real odd one to get stuck on but weirdly I am.

You you have a imageView containing a image. You size that imageView down and then tell it to use UIViewContentModeScaleAspectFit. so your imageView might be 300 by 200 but your scaled image within could be 300 by 118 or 228 by 200 because its aspectfit.

How on earth do you get the size of the actual image?
imageView.image.size is the size of the original image.
imageview.frame is the frame of the imageview not the contained image.
imageview.contentstretch does not work either

like image 513
Burf2000 Avatar asked Jul 28 '11 09:07

Burf2000


1 Answers

I have written a quick category on UIImageView to achieve that:

(.h)

@interface UIImageView (additions) - (CGSize)imageScale; @end 

(.m)

@implementation UIImageView (additions) - (CGSize)imageScale {     CGFloat sx = self.frame.size.width / self.image.size.width;     CGFloat sy = self.frame.size.height / self.image.size.height;     CGFloat s = 1.0;     switch (self.contentMode) {         case UIViewContentModeScaleAspectFit:             s = fminf(sx, sy);             return CGSizeMake(s, s);             break;          case UIViewContentModeScaleAspectFill:             s = fmaxf(sx, sy);             return CGSizeMake(s, s);             break;          case UIViewContentModeScaleToFill:             return CGSizeMake(sx, sy);          default:             return CGSizeMake(s, s);     } } @end 

Multiply the original image size by the given scale, and you'll get your actual displayed image size.

like image 104
Cyrille Avatar answered Oct 16 '22 22:10

Cyrille