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.
Here are CGSize and CGRect extensions for fitting a size within another size and fitting a rect within another rect respectively:
I wrote a function that should achieve what you desire.
It will return the
CGRect
of a giveninnerRect
, after scaling it to fit within a givenouterRect
, while maintaining aspect ratio. TheinnerRect
will be centered within theouterRect
.You can then use this like so:
In this case, the
innerRect
is too wide for theouterRect
, so it will be scaled according to it's width.Here, the red area is the
innerRect
and the green area is theouterRect
. They both originally had the same height, but after being scaled down (as it was 2x as wide), theinnerRect
now has half the height of theouterRect
.Here the
innerRect
is added as a subview to theouterRect
. If you want to add them to the same superview, you can pass theouterRect
'sframe
into the function, rather than thebounds
.I think This helps You.