Last active
October 25, 2020 03:23
-
-
Save laevandus/b47ceb9b64b4581905adf182f267627c to your computer and use it in GitHub Desktop.
This file contains 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 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