I want to insert one view into another with aspect fit option. But I can't just set contentMode for some reasons.
Could you provide a solution via resizing of the inner CGRect according to the outer CGRect?
And yes, there are a lot of similar questions but no one provides such solution.
I wrote a function that should achieve what you desire.
It will return the
CGRectof a giveninnerRect, after scaling it to fit within a givenouterRect, while maintaining aspect ratio. TheinnerRectwill be centered within theouterRect.You can then use this like so:
In this case, the
innerRectis too wide for theouterRect, so it will be scaled according to it's width.Here, the red area is the
innerRectand the green area is theouterRect. They both originally had the same height, but after being scaled down (as it was 2x as wide), theinnerRectnow has half the height of theouterRect.Here the
innerRectis added as a subview to theouterRect. If you want to add them to the same superview, you can pass theouterRect'sframeinto the function, rather than thebounds.