Skip to content

Instantly share code, notes, and snippets.

@jkosoy
Last active June 3, 2023 18:11
Show Gist options
  • Save jkosoy/c835fea2c03e76720c77 to your computer and use it in GitHub Desktop.
Save jkosoy/c835fea2c03e76720c77 to your computer and use it in GitHub Desktop.
Aspect Fill and Aspect Fit calculations in Swift
// port of http://stackoverflow.com/a/17948778/3071224
import UIKit
import Foundation
extension CGSize {
static func aspectFit(aspectRatio : CGSize, var boundingSize: CGSize) -> CGSize {
let mW = boundingSize.width / aspectRatio.width;
let mH = boundingSize.height / aspectRatio.height;
if( mH < mW ) {
boundingSize.width = boundingSize.height / aspectRatio.height * aspectRatio.width;
}
else if( mW < mH ) {
boundingSize.height = boundingSize.width / aspectRatio.width * aspectRatio.height;
}
return boundingSize;
}
static func aspectFill(aspectRatio :CGSize, var minimumSize: CGSize) -> CGSize {
let mW = minimumSize.width / aspectRatio.width;
let mH = minimumSize.height / aspectRatio.height;
if( mH > mW ) {
minimumSize.width = minimumSize.height / aspectRatio.height * aspectRatio.width;
}
else if( mW > mH ) {
minimumSize.height = minimumSize.width / aspectRatio.width * aspectRatio.height;
}
return minimumSize;
}
}
// to determine the calculated size of a UIImage
let sizeBeingScaledTo = CGSizeAspectFit(myImage.size, myImageView.frame.size);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment