Resize CGSize to the maximum while maintaining aspect ratio

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

There are several objects whose size exceeds 900 * 900, and I want to write a function that resizes them to the maximum (as I said, a maximum of 900 * 900), but to maintain the aspect ratio.

For example: if I have an object with a width of 1000 pixels and a height of 1000 pixels, I want the function to return an object of 900 * 900. If I have an object with a width of 1920px and a height of 1080px, I want it to return the maximum size while preserving the ratio.

Does anyone know how I can do this?

Thank!

Reply to original User2:

I tried this code:

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

let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect)

final {x 420 y 0 w 1,080 h 1,080}, , x = 420, 1080*1080 1920*1080 , 900*900.

?

+4
2

, AVMakeRectWithAspectRatioInsideRect AVFounation, .

, . boundingRect: , - aspectRatio: , , .

:

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

( , AVMakeRect(aspectRatio:insideRect:) Swift 3)

+4

, :

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
}

900 - , , .

+1

All Articles