UIImage size in UIImageView
ios, iphone, objective-c, uiimage
Solution
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
Problem
I have some `UIImage` and display it in `UIImageView`. I need to use `UIViewContentModeScaleAspectFit` content mode. Here is simple code: ``` UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; imageView.image = self.image; imageView.contentMode = UIViewContentModeScaleAspectFit; [self.view addSubview:imageView]; [imageView release]; ``` How to know the size of an image which is displayed on the screen? Are there any solutions, properties or shall i calculate it manually? EDIT: I know about the property `image.size`. `self.image.size` ->>> Original image size `imageView.image.size` ->>> Size of the imageView, but not the displayed image. I ask about the displayed size depending on the `imageView's size` and it's `contentmode`.