Skip to content

Instantly share code, notes, and snippets.

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