Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active October 25, 2020 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/b47ceb9b64b4581905adf182f267627c to your computer and use it in GitHub Desktop.
Save laevandus/b47ceb9b64b4581905adf182f267627c to your computer and use it in GitHub Desktop.
extension CGRect {
func scaled(toFillSize targetSize: CGSize) -> CGRect {
var scaledRect = self
switch (size.aspect, targetSize.aspect) {
case (.portrait, .portrait), (.portrait, .square):
scaledRect.size.height = width / targetSize.aspectRatio
scaledRect.size.width = width
if scaledRect.height > height {
scaledRect.size = size
}
scaledRect.origin.y -= (scaledRect.height - height) / 2.0
case (.portrait, .landscape), (.square, .landscape):
scaledRect.size.height = width / targetSize.aspectRatio
scaledRect.size.width = width
if scaledRect.height > height {
scaledRect.size = size
}
scaledRect.origin.y -= (scaledRect.height - height) / 2.0
case (.landscape, .portrait), (.square, .portrait):
scaledRect.size.height = height
scaledRect.size.width = height * targetSize.aspectRatio
if scaledRect.width > width {
scaledRect.size = size
}
scaledRect.origin.x -= (scaledRect.width - width) / 2.0
case (.landscape, .landscape), (.landscape, .square):
scaledRect.size.height = height
scaledRect.size.width = height * targetSize.aspectRatio
if scaledRect.size.width > width {
scaledRect.size = size
}
scaledRect.origin.x -= (scaledRect.width - width) / 2.0
case (.square, .square):
return self
}
return scaledRect.integral
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment