Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.