Created
September 27, 2016 05:38
-
-
Save nkurapati/122857a39150b671a80de87bc100c231 to your computer and use it in GitHub Desktop.
Calculate Image Aspect Fit size according to available space width and Height
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
function getImageAspectFit(originalWidth, originalHeight, availableWidth, availableHeight) { | |
var newSize = []; | |
//Solution One: | |
if(originalWidth > originalHeight){ | |
newSize["width"] = (availableWidth < originalWidth) ? availableWidth : originalWidth | |
newSize["height"] = (originalHeight / originalWidth) * newSize["width"]! | |
} else if(originalWidth < originalHeight) { | |
newSize["height"] = (availableHeight < originalHeight) ? availableHeight : originalHeight | |
newSize["width"] = (originalWidth / originalHeight ) * newSize["height"]! | |
} else { | |
if(availableWidth < availableHeight){ | |
newSize["width"] = (availableWidth < originalWidth) ? availableWidth : originalWidth | |
newSize["height"] = (originalHeight / originalWidth) * newSize["width"]! | |
} else { | |
newSize["height"] = (availableHeight < originalHeight) ? availableHeight : originalHeight | |
newSize["width"] = (originalWidth / originalHeight ) * newSize["height"]! | |
} | |
} | |
//Solution Two: | |
if(availableWidth < availableHeight){ | |
newSize["width"] = (availableWidth < originalWidth) ? availableWidth : originalWidth | |
newSize["height"] = (originalHeight / originalWidth) * newSize["width"]! | |
} else { | |
newSize["height"] = (availableHeight < originalHeight) ? availableHeight : originalHeight | |
newSize["width"] = (originalWidth / originalHeight ) * newSize["height"]! | |
} | |
return newSize | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment