[ios] UIImageView aspect fit and center

I have an image view, declared programmatically, and I am setting its image, also programmatically.

However, I find myself unable to set the image to both fit the aspect and align centre to the image view.

In other words, I want the image to:

  • Scale down to fit the aspect, if the image is large.
  • Centre but not scale up, if the image is small.

How do I get that?

This question is related to ios objective-c uiimageview uiimage

The answer is


[your_imageview setContentMode:UIViewContentModeCenter];

Updated answer

When I originally answered this question in 2014, there was no requirement to not scale the image up in the case of a small image. (The question was edited in 2015.) If you have such a requirement, you will indeed need to compare the image's size to that of the imageView and use either UIViewContentModeCenter (in the case of an image smaller than the imageView) or UIViewContentModeScaleAspectFit in all other cases.

Original answer

Setting the imageView's contentMode to UIViewContentModeScaleAspectFit was enough for me. It seems to center the images as well. I'm not sure why others are using logic based on the image. See also this question: iOS aspect fit and center


You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

This subclass uses center if the image is not larger than the view, otherwise it scales down. I found this useful for a UIImageView that changes the size.

The image it displays is smaller than the view for large sizes, but larger than the view for small sizes. I want it only to scale down, but not up.

class CenterScaleToFitImageView: UIImageView {
    override var bounds: CGRect {
        didSet {
            adjustContentMode()
        }
    }

    override var image: UIImage? {
        didSet {
            adjustContentMode()
        }
    }

    func adjustContentMode() {
        guard let image = image else {
            return
        }
        if image.size.width > bounds.size.width ||
            image.size.height > bounds.size.height {
            contentMode = .ScaleAspectFit
        } else {
            contentMode = .Center
        }
    }
}

In swift language we can set content mode of UIImage view like following as:

let newImgThumb = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
newImgThumb.contentMode = .scaleAspectFit

For people looking for UIImage resizing,

@implementation UIImage (Resize)

- (UIImage *)scaledToSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)aspectFitToSize:(CGSize)size
{
    CGFloat aspect = self.size.width / self.size.height;
    if (size.width / aspect <= size.height)
    {
        return [self scaledToSize:CGSizeMake(size.width, size.width / aspect)];
    } else {
        return [self scaledToSize:CGSizeMake(size.height * aspect, size.height)];
    }
}

- (UIImage *)aspectFillToSize:(CGSize)size
{
    CGFloat imgAspect = self.size.width / self.size.height;
    CGFloat sizeAspect = size.width/size.height;

    CGSize scaledSize;

        if (sizeAspect > imgAspect) { // increase width, crop height
            scaledSize = CGSizeMake(size.width, size.width / imgAspect);
        } else { // increase height, crop width
            scaledSize = CGSizeMake(size.height * imgAspect, size.height);
        }
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

Swift

yourImageView.contentMode = .center

You can use the following options to position your image:

  • scaleToFill
  • scaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
  • redraw // redraw on bounds change (calls -setNeedsDisplay)
  • center // contents remain same size. positioned adjusted.
  • top
  • bottom
  • left
  • right
  • topLeft
  • topRight
  • bottomLeft
  • bottomRight

I solved this problem like this.

  1. setImage to UIImageView (with UIViewContentModeScaleAspectFit)
  2. get imageSize (CGSize imageSize = imageView.image.size)
  3. UIImageView resize. [imageView sizeThatFits:imageSize]
  4. move position where you want.

I wanted to put UIView on the top center of UICollectionViewCell. so, I used this function.

- (void)setImageToCenter:(UIImageView *)imageView
{
    CGSize imageSize = imageView.image.size;
    [imageView sizeThatFits:imageSize];
    CGPoint imageViewCenter = imageView.center;
     imageViewCenter.x = CGRectGetMidX(self.contentView.frame);
    [imageView setCenter:imageViewCenter];
}

It works for me.


Just pasting the solution:

Just like @manohar said

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentModeScaleAspectFit;
}

solved my problem


let bannerImageView = UIImageView();
bannerImageView.contentMode = .ScaleAspectFit;
bannerImageView.frame = CGRectMake(cftX, cftY, ViewWidth, scrollHeight);

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uiimageview

Programmatically change the height and width of a UIImageView Xcode Swift How to set image in circle in swift How to load GIF image in Swift? How to assign an action for UIImageView object in Swift How to set corner radius of imageView? How do you create a UIImage View Programmatically - Swift UIImageView aspect fit and center Resize UIImage and change the size of UIImageView How to view .img files? iOS - UIImageView - how to handle UIImage image orientation

Examples related to uiimage

Crop image to specified size and picture location Convert UIImage to NSData and convert back to UIImage in Swift? How can I color a UIImage in Swift? How to Resize image in Swift? How to set image for bar button with swift? How do you create a UIImage View Programmatically - Swift Navigation bar with UIImage for title Loading/Downloading image from URL on Swift How can I change image tintColor in iOS and WatchKit UIImageView aspect fit and center