Last active
June 3, 2023 18:11
-
-
Save jkosoy/c835fea2c03e76720c77 to your computer and use it in GitHub Desktop.
Aspect Fill and Aspect Fit calculations in Swift
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
// 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; | |
} | |
} |
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
// 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