How to get the displayed image frame from UIImageView?
If it's UIViewContentModeScaleAspectFit
, it's something like this:
UIImageView *iv; // your image view
CGSize imageSize = iv.image.size;
CGFloat imageScale = fminf(CGRectGetWidth(iv.bounds)/imageSize.width, CGRectGetHeight(iv.bounds)/imageSize.height);
CGSize scaledImageSize = CGSizeMake(imageSize.width*imageScale, imageSize.height*imageScale);
CGRect imageFrame = CGRectMake(roundf(0.5f*(CGRectGetWidth(iv.bounds)-scaledImageSize.width)), roundf(0.5f*(CGRectGetHeight(iv.bounds)-scaledImageSize.height)), roundf(scaledImageSize.width), roundf(scaledImageSize.height));
Use this api from AVFoundation
#import <AVFoundation/AVFoundation.h>
CGRect imageRect =
AVMakeRectWithAspectRatioInsideRect(imageView.image.size, imageView.bounds);
In fact, it's built-in since iOS 4 (for UIViewContentModeScaleAspectFit
):
@import AVFoundation;
AVMakeRectWithAspectRatioInsideRect(imageView.image.size, imageView.bounds);
Since frame components may be not round numbers, consider wrapping the call by
CGRectIntegral(…)
See http://nshipster.com/image-resizing/ for more tricks.