Skip to content

Instantly share code, notes, and snippets.

@FlexMonkey
Created January 12, 2016 15:51
Show Gist options
  • Save FlexMonkey/e4c004b5a7a2897f6435 to your computer and use it in GitHub Desktop.
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
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)
}
}
@memononen
Copy link

I think you should be able to simplify the calculation of scale:

let scale = min(target.width / self.width, target.height / self.height)

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment