James
James

Reputation: 6499

Resize image to fit proportions

In the design of my app, I have a square space for an image that comes from a remote server. However, occasionally the image is a landscape rectangle instead of a square.

I don't want to crop the image, but instead scale it down far enough to fit inside the square constraints, then fill in the remaining space with some background color, white maybe.

Upvotes: 2

Views: 3585

Answers (3)

Joshua Dance
Joshua Dance

Reputation: 10482

Create a UIImageView with a background color of the color you want. Create your image from your server, set the image in the image view, and then set the contentMode = UIViewContentModeScaleAspectFit

UIImageView *backgroundColorWhite = [[UIImageView alloc] initWithFrame:someObject.frame];
backgroundColorWhite.backgroundColor = [UIColor whiteColor];
UIImage *serverImage = [UIImage imageWithData:serverData];
backgroundColorWhite.contentMode = UIViewContentModeScaleAspectFit;
[backgroundColorWhite setImage:serverImage];

Upvotes: 1

Aaron Hayman
Aaron Hayman

Reputation: 8502

I don't know if this helps or not, but I use this to fit the size of the View to match the image. It takes the provided rect, and trims it to match the image. The returned CGRect can be then be applied to the view. I used this so I could add a shadow to the image (which looks wrong if the view doesn't match the image perfectly).

- (CGRect) resizeCGRect:(CGRect)rect toImage:(UIImage *)image{
CGSize size = rect.size;
CGSize iSize = image.size;
if (iSize.width > iSize.height){
    if (iSize.width / iSize.height > size.width / size.height)
        size.height = size.width * (iSize.height / iSize.width);                    
    else
        size.width = size.height * (iSize.width / iSize.height);
} else {
    if (iSize.height / iSize.width > size.height / size.width) 
        size.width = size.height * (iSize.width / iSize.height);
    else 
        size.height = size.width * (iSize.height / iSize.width);
}
rect.size = size;
return rect;

}

Upvotes: 1

rishi
rishi

Reputation: 11839

Set the contentMode of your UIImageView to UIViewContentModeScaleAspectFit.

Upvotes: 5

Related Questions