Hidden AVFoundation Gem
I’ve probably written aspect ratio code a hundred times. Each time I approach the topic, I write a quick and dirty implementation, get it wrong, debug it with pencil & paper, and then fix my mistake.
Since this is something I need sparingly, I figure it’s not worth pulling in a library, or trying to find a reference implementation.
A couple years ago I came across
AVMakeRect, which is a built-in function to do exactly that!
Usage is simple:
let screenRect = CGRect(x: 0, y: 0, width: 1024, height: 768) let aspectRatio = CGSize(width: 16, height: 9) AVMakeRect(aspectRatio: aspectRatio, insideRect: screenRect)
This returns to you the largest rect that fits inside the specified rect, while constraining the rect to the aspect ratio. Extra super bonus points: It even centers the rect for you.
You can find the docs here.
Cheers to the engineer who added this. 🍻