Created
September 24, 2018 10:15
-
-
Save fewlinesofcode/d4eb5904eee6670d96383858767cba32 to your computer and use it in GitHub Desktop.
Aspect correct resizing
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 CGSize { | |
enum AspectMode { | |
case fit | |
case fill | |
} | |
enum Orientation { | |
case portrait | |
case landscape | |
} | |
func aspectCorrectSizeToFit(targetSize: CGSize, aspectMode: AspectMode = .fill) -> CGSize { | |
switch aspectMode { | |
case .fill: return aspectFill(targetSize: targetSize) | |
case .fit: return aspectFit(targetSize: targetSize) | |
} | |
} | |
var orientation: Orientation { | |
if height >= width { return .portrait } | |
else { return .landscape } | |
} | |
func aspectFit(targetSize: CGSize) -> CGSize { | |
let wRatio = targetSize.width / width | |
let hRatio = targetSize.height / height | |
let scale = min(wRatio, hRatio) | |
return applying(CGAffineTransform(scaleX: scale, y: scale)) | |
} | |
func aspectFill(targetSize: CGSize) -> CGSize { | |
let wRatio = targetSize.width / width | |
let hRatio = targetSize.height / height | |
let scale = max(wRatio, hRatio) | |
return applying(CGAffineTransform(scaleX: scale, y: scale)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment