I have this UIImageView
and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio and any resolution) and I want it to fit in the borders, so the picture does not exceed them, but it can shrink them as it wants. (marked red in the picture):
Right now the image fits the necessary size properly, but I have 2 worries:
1. The UIImageView
is not equal the size of the resized image, thus leaving red background (and I don't want that)
2. If the image is smaller that the height of my UIImageView
it is not resized to be smaller, it stays the same height.
Here's my code and I know its wrong:
UIImage *actualImage = [attachmentsArray lastObject];
UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)];
attachmentImageNew.image = actualImage;
attachmentImageNew.backgroundColor = [UIColor redColor];
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;
So how do I dynamically change the size not only of the UIImageView.image
, but of the whole UIImageView
, thus making its size totally adjustable to its content. Any help would be much appreciated, thanks!
If you have the size of the image, why don't you set the
frame.size
of the image view to be of this size?EDIT----
Ok, so seeing your comment I propose this:
This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.
PS: I hope you're setting
imageView.layer.shouldRasterise = YES
andimageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.
I think what you want is a different
content mode
. Try usingUIViewContentModeScaleToFill
. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.Have a look to the
content mode
section on the official doc to get a better idea of the different content mode available (it is illustrated with images).This is the Swift equivalent for Rajneesh071's answer, using extensions
Usage:
Use the category below and then apply border from Quartz into your image:
The category: UIImage+AutoScaleResize.h
UIImage+AutoScaleResize.m