简体   繁体   中英

Resize image maintaining aspect ratio

I am developing an app where in users click images and upload them. There is a button in my app and on clicking it, the camera mode opens. User can click image and see preview. In preview the image looks good and it occupies whole screen. Later I have to display this image in a UIImageView of width 110 and height 111. When I display it in this, the image is getting distorted and cropped at edges. My main objective is to maintain aspect ratio.

I tried doing this.

- (void)displayCapturedImage
{
//[self.imageView setImage:self.capturedImage];
    CGSize smallSize = CGSizeMake(110, 111);
    [self.imageView setImage:[self imageWithImage:self.capturedImage scaledToSize:smallSize]];

}

- (UIImage*)imageWithImage:(UIImage*)image
          scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

but this didn't work for me. Image is still distorted.

You need to calculate the scale ratio yourself. Determine how much smaller the image needs to be and apply that to both the width and height.

Something like

float widthFactor  = targetWidth / width;
            float heightFactor = targetHeight / height;

            if ( widthFactor < heightFactor )
                scaleFactor = widthFactor;
            else
                scaleFactor = heightFactor;

            scaledWidth  = width  * scaleFactor;
            scaledHeight = height * scaleFactor;

            if ( widthFactor < heightFactor )
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

            else if ( widthFactor > heightFactor )
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

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