Last active
May 22, 2017 07:54
-
-
Save nicolas-miari/57409ef4b1a1995cbf5b to your computer and use it in GitHub Desktop.
UIImage Calculate On-Screen Size (UIImageView: AspectFit)
This file contains hidden or 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 UIImage { | |
/** | |
Calculates the resulting size (rendered on screen) of the receiver when it | |
is displayed within a `UIImageView` instance of bounds size `containerSize` | |
that has its `contentMode` property set to `.ScaleAspectFit`. | |
- parameter contanerSize: The size of the hypothetical UIImageView instance | |
that is to display the receiver on screen. | |
- returns: the effective size at which the receiver would be rendered on | |
screen if displayed in said view. | |
*/ | |
func scaleAspectFitSizeWhenEmbeddedInSize(containerSize: CGSize) -> CGSize { | |
let imageSize = self.size | |
let imageRatio = imageSize.width / imageSize.height | |
let containerRatio = containerSize.width / containerSize.height | |
if imageRatio < containerRatio { | |
let scale = containerSize.height / imageSize.height | |
let width = scale * imageSize.width | |
return CGSizeMake(width, containerSize.height) | |
} else{ | |
let scale = containerSize.width / imageSize.width | |
let height = scale * imageSize.height | |
return CGSizeMake(containerSize.width, height) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment