I have some UIImage
and display it in UIImageView
.
I need to use UIViewContentModeScaleAspectFit
content mode.
Here i
Here's a category on UIImageView
that you can use to introspect the bounds of the displayed image based on the UIViewContentMode
set on the image view:
@implementation UIImageView (JRAdditions)
- (CGRect)displayedImageBounds {
UIImage *image = [self image];
if(self.contentMode != UIViewContentModeScaleAspectFit || !image)
return CGRectInfinite;
CGFloat boundsWidth = [self bounds].size.width,
boundsHeight = [self bounds].size.height;
CGSize imageSize = [image size];
CGFloat imageRatio = imageSize.width / imageSize.height;
CGFloat viewRatio = boundsWidth / boundsHeight;
if(imageRatio < viewRatio) {
CGFloat scale = boundsHeight / imageSize.height;
CGFloat width = scale * imageSize.width;
CGFloat topLeftX = (boundsWidth - width) * 0.5;
return CGRectMake(topLeftX, 0, width, boundsHeight);
}
CGFloat scale = boundsWidth / imageSize.width;
CGFloat height = scale * imageSize.height;
CGFloat topLeftY = (boundsHeight - height) * 0.5;
return CGRectMake(0, topLeftY, boundsWidth, height);
}
@end