How to get the displayed image frame from UIImageView?

I modify the UIImageView's contentMode property. So my image's frame is not equal to the frame of UIImageView. My problem is how to retrive the image's frame from UIImageView.

As the following example, the orange rectangle is the UIImageView's border. It is obviously that the frame of image is not the same as UIImageView.

图1


如果它是UIViewContentModeScaleAspectFit ,它就像这样:

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));

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.


使用AVFoundation的这个api
#import <AVFoundation/AVFoundation.h> CGRect imageRect = AVMakeRectWithAspectRatioInsideRect(imageView.image.size, imageView.bounds);

链接地址: http://www.djcxy.com/p/81994.html

上一篇: 在哪里确定UIView大小

下一篇: 如何从UIImageView获取显示的图像帧?