LightNight
LightNight

Reputation: 1625

Proportionally resize UIImage by width

I need to resize UIImage proportionally by width, may be someone have a working code?

For ex.:

Input: Width: 900 Height: 675. Resize to width: 400 width

Result: Width: 400 Height: 300

Please help..

Upvotes: 4

Views: 4254

Answers (2)

meds
meds

Reputation: 22976

Couldn't you just set the content mode? to .ScaleAspectFill? Then you can set the UIImageView size to any arbitrary size and the aspect ratio will be preserved.

https://developer.apple.com/reference/uikit/uiviewcontentmode/1622518-scaleaspectfill

Upvotes: 1

Damian Carrillo
Damian Carrillo

Reputation: 1218

Check this blog post out. In particular, these two files:

Maybe this would work for you:

UIImage *image = [UIImage imageNamed:@"SomeImage-900x675"]; // SomeImage-900x675.png
CGFloat targetWidth = 400.0f;

CGFloat scaleFactor = targetWidth / image.size.width;
CGFloat targetHeight = image.size.height * scaleFactor;
CGSize targetSize = CGSizeMake(targetWidth, targetHeight);

UIImage *scaledImage = [image resizedImage:targetSize interpolationQuality:kCGInterpolationHigh];

Upvotes: 7

Related Questions