Skip to content

Instantly share code, notes, and snippets.

@westerlund
Created May 11, 2016 08:10
Show Gist options
  • Save westerlund/2c07b9559a8f2bbf1692b0dcc7d4aea8 to your computer and use it in GitHub Desktop.
Save westerlund/2c07b9559a8f2bbf1692b0dcc7d4aea8 to your computer and use it in GitHub Desktop.
CGRect + resize keeping aspect
extension CGRect {
func resized(size: CGSize, aspectFill: Bool) -> CGRect {
var resizedRect = CGRect.zero;
let aspectWidth = size.width / self.size.width
let aspectHeight = size.height / self.size.height
let aspectRatio = aspectFill ? max(aspectWidth, aspectHeight) : min(aspectWidth, aspectHeight)
resizedRect.size.width = self.size.width * aspectRatio
resizedRect.size.height = self.size.height * aspectRatio
resizedRect.origin.x = (size.width - resizedRect.size.width) / 2
resizedRect.origin.y = (size.height - resizedRect.size.height) / 2
return resizedRect
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment