UIImageView aspect fit and center

IosObjective CUiimageviewUiimage

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

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

Solution 3 - Ios

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

Solution 4 - Ios

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: https://stackoverflow.com/questions/7049105/ios-aspect-fit-and-center

Solution 5 - Ios

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.

Solution 6 - Ios

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

Solution 7 - Ios

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
        }
    }
}

Solution 8 - Ios

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

Solution 9 - Ios

[your_imageview setContentMode:UIViewContentModeCenter];

Solution 10 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavi VoodaView Question on Stackoverflow
Solution 1 - IosRavi VoodaView Answer on Stackoverflow
Solution 2 - IosAli RazaView Answer on Stackoverflow
Solution 3 - IosJonas DeichelmannView Answer on Stackoverflow
Solution 4 - IosNate CookView Answer on Stackoverflow
Solution 5 - IosNicejinuxView Answer on Stackoverflow
Solution 6 - IosManishView Answer on Stackoverflow
Solution 7 - IosorkodenView Answer on Stackoverflow
Solution 8 - IosAntony OusephView Answer on Stackoverflow
Solution 9 - IossouvickcseView Answer on Stackoverflow
Solution 10 - IoskarimView Answer on Stackoverflow