Resize CGSize to the maximum with keeping the aspect-ratio

This code can be greatly reduced and modified, but for clarity's sake:

if myImage.width == myImage.height {
    // New image will be 900px by 900px
    newImage.width = (900 / myImage.width) * myImage.width
    newImage.height = (900 / myImage.height) * myImage.height
} else if myImage.width > myImage.height {
    // New image will have width of 900px
    newImage.width = (900 / myImage.width) * myImage.width
    newImage.height = (900 / myImage.width) * myImage.height
} else {
    // New Image will have height of 900px
    newImage.width = (900 / myImage.height) * myImage.width
    newImage.height = (900 / myImage.height) * myImage.height
}

In this snippet, 900 is the maximum width and height of the resized image, but this value can be abstracted with a variable for any value you would like.


You can use the AVMakeRect(aspectRatio:insideRect:) 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 insideRect: 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 which you want to preserve the aspect ratio of.
let aspect = CGSize(width: 1920, height: 1080)

// Rect to fit that size within. 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 result = AVMakeRect(aspectRatio: aspect, insideRect: rect).size