Skip to content

Instantly share code, notes, and snippets.

@fewlinesofcode
Created September 24, 2018 10:15
Show Gist options
  • Save fewlinesofcode/d4eb5904eee6670d96383858767cba32 to your computer and use it in GitHub Desktop.
Save fewlinesofcode/d4eb5904eee6670d96383858767cba32 to your computer and use it in GitHub Desktop.
Aspect correct resizing
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