Created
January 12, 2016 15:51
-
-
Save FlexMonkey/e4c004b5a7a2897f6435 to your computer and use it in GitHub Desktop.
aspectFitInRect() - returns biggest rect of current aspect ratio that will fit into target
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension CGRect | |
{ | |
func aspectFitInRect(target target: CGRect) -> CGRect | |
{ | |
let scale: CGFloat = | |
{ | |
let scale = target.width / self.width | |
return self.height * scale <= target.height ? | |
scale : | |
target.height / self.height | |
}() | |
let width = self.width * scale | |
let height = self.height * scale | |
let x = target.midX - width / 2 | |
let y = target.midY - height / 2 | |
return CGRect(x: x, | |
y: y, | |
width: width, | |
height: height) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you should be able to simplify the calculation of scale:
The rationale is that you have two scaling values, each of them is going to scale the target to one of the dimensions of the rect. The smaller one guarantees that the other dimension does not overflow.