F.SO4 F.SO4 - 2 years ago 124
Swift Question

Resize CGSize to the maximum with keeping the aspect-ratio

I have a

objects that I need to send to my server. The maximum size I can send to the server is 900*900 (900 width/900 height).

There are some objects that are larger the 900*900 and I want to write a function that resizes them to the maximum (as I already say, the maximum is 900*900) but to keep the aspect ratio.

For example: if I have an object that is 1,000px width and 1,000px height I want the function to return a 900*900 object. If I have an object that is 1920px width and 1080px height I want it to return the maximum size possible with keeping the ratio.

Anyone have any idea how can I do that?

Thank you!

OriginalUser2 answer:

I've tried this code:

let aspect = CGSizeMake(900, 900)
let rect = CGRectMake(0, 0, 1920, 1080)

let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect)

{x 420 y 0 w 1,080 h 1,080}
, I can't understand why the
x = 420
, but anyway
is not in the same aspect ratio as
and it's bigger than

Can you explain a bit more?

Answer Source

Like I said in my comment, you can use the AVMakeRectWithAspectRatioInsideRect function from the AVFounation framework in order to do this.

The problem with your code is that the values are round the wrong way. The boundingRect: parameter should be the rect to fit your size within – and the aspectRatio: should be the original size that you want to be scaled while maintaining aspect ratio.

For example:

import AVFoundation

// original size
let aspect = CGSize(width: 1920, height: 1080)

// rect to fit that size within, while maintaining its aspect ratio,
// in this case you don't care about fitting inside a rect, so pass (0, 0) for the origin
let rect = CGRect(x: 0, y: 0, width: 900, height: 900)

// aspect fitted size, in this case (900.0, 506.25)
let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect).size

(note that the function has been renamed to AVMakeRect(aspectRatio:insideRect:) in Swift 3)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download