简体   繁体   中英

How to resize an UIImage while maintaining its Aspect Ratio

I want to resize a UIImage with maintaining its Aspect Ratio. I have written the following code, but it is not working as expected.

Code

-(UIImage * ) scaleImage: (UIImage * ) image toSize: (CGSize) targetSize {

    CGFloat scaleFactor = 1.0;
    if (image.size.width > targetSize.width || image.size.height > targetSize.height)
        if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
            scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
    UIGraphicsBeginImageContext(targetSize);
    CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2, (targetSize.height - image.size.height * scaleFactor) / 2,
        image.size.width * scaleFactor, image.size.height * scaleFactor);
    [image drawInRect: rect];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

What exactly is wrong here?

I'm using something similar to this in a few projects:

- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize scaledSize = newSize;
    float scaleFactor = 1.0;
    if( image.size.width > image.size.height ) {
        scaleFactor = image.size.width / image.size.height;
        scaledSize.width = newSize.width;
        scaledSize.height = newSize.height / scaleFactor;
    }
    else {
        scaleFactor = image.size.height / image.size.width;
        scaledSize.height = newSize.height;
        scaledSize.width = newSize.width / scaleFactor;
    }

    UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
    [image drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    return scaledImage;
}

If this is for displaying in a UI, you can use Interface Builder and specify the "Aspect Fit" property.

You can also do this in code by setting the content mode to UIViewContentModeScaleAspectFit :

imageView.contentMode = UIViewContentModeScaleAspectFit;

This method takes an image and a max dimension. If the max original image dimension is less than the specified max dimension, you get the original back so it won't get blown up. Otherwise, you get a new image having a max dimension of the one specified and the other determined by the original aspect ratio. So as an example, if you give it a 1024x768 image and max dimension of 640 you get back a 640x480 version, if you give it a 768x1024 image and max dimension of 640 you get back a 480x640 version.

- (UIImage *)resizeImage:(UIImage *)image
        withMaxDimension:(CGFloat)maxDimension
{
    if (fmax(image.size.width, image.size.height) <= maxDimension) {
        return image;
    }

    CGFloat aspect = image.size.width / image.size.height;
    CGSize newSize;

    if (image.size.width > image.size.height) {
        newSize = CGSizeMake(maxDimension, maxDimension / aspect);
    } else {
        newSize = CGSizeMake(maxDimension * aspect, maxDimension);
    }

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 1.0);
    CGRect newImageRect = CGRectMake(0.0, 0.0, newSize.width, newSize.height);
    [image drawInRect:newImageRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

In my case (I wanted to have an image in a UIView) and keep the ratio with auto layout the way described here was great. The most important part of the article for me was (almost quoting):

constraint = [NSLayoutConstraint constraintWithItem:self.imageView
                                          attribute:NSLayoutAttributeHeight
                                          relatedBy:NSLayoutRelationEqual
                                             toItem:self.imageView 
                                          attribute:NSLayoutAttributeWidth 
                                         multiplier:ration 
                                           constant:0.0f];

[self.imageView addConstraint:constraint];

the only thing is to calculate the ratio according to the actual width and height of image. I found this way easy and elegant.

- (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    float ratio = newSize.width/image.size.width;
    [image drawInRect:CGRectMake(0, 0, newSize.width, ratio * image.size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"New Image Size : (%f, %f)", newImage.size.width, newImage.size.height);
    UIGraphicsEndImageContext();
    return newImage;
}

In Swift 5 you can use scaleAspectFit on the contentMode attribute.

let photo = UIImage(imageLiteralResourceName: "your_img_name")
let photoImageView = UIImageView(image: photo)     
        
photoImageView.contentMode = .scaleAspectFit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM