AVMakeRectWithAspectRatioInsideRect
I have recently discovered this method through a work colleague. I have been manually computing the size that fits a CGRect but maintains aspect ratio before, but this method will easily replace that. This is one of the benefits of working with new iOS developers every now and then; you get to discover new things that will make development easier.
Note that the center of the CGRect returned by this function is the same as the center of the boundingRect passed in the function.
Use Cases
According to Apple Documentation:
This is useful when attempting to fit the presentationSize property of an AVPlayerItem within the bounds of another CALayer. You would typically use the return value of this function as an AVPlayerLayer frame property value.
This is also useful if you want to present a view on top of the exact size of a UIImage displayed in a UIImageView, with aspect fit mode.
How to use
Do not forget to include the AVFoundation framework.
Try this in a Playground:
1 2 3 4 5 6 7 8 |
//: Playground - noun: a place where people can play import AVFoundation let imageSizeSameAspectRatio = CGSize(width: 50, height: 100) let imageSizeDiffAspectRatio = CGSize(width: 70, height: 70) let containerViewRect = CGRect(x: 0, y: 0, width: 100, height: 200) AVMakeRectWithAspectRatioInsideRect(imageSizeSameAspectRatio, containerViewRect) // Returns {x 0 y 0 w 100 h 200} AVMakeRectWithAspectRatioInsideRect(imageSizeDiffAspectRatio, containerViewRect) // Returns {x 0 y 50 w 100 h 100} |