Skip to content

Instantly share code, notes, and snippets.

@benhylau
Created October 7, 2014 15:30
Show Gist options
  • Save benhylau/b75802ceacb221ba8240 to your computer and use it in GitHub Desktop.
Save benhylau/b75802ceacb221ba8240 to your computer and use it in GitHub Desktop.
/**
* Gets the size of content fitted inside a container while maintaining its aspect ratio.
*
* @param containerWidth width of the container.
* @param containerHeight height of the container.
* @param contentWidth width of the content.
* @param contentHeight height of the content.
* @return a {@link Point} where the (x, y) corresponds to the (width, height) of the content fitted inside the
* container.
*/
public static Point getAspectFitSize(int containerWidth, int containerHeight, int contentWidth, int contentHeight) {
int fittedContentWidth = containerWidth;
int fittedContentHeight = containerHeight;
// Compare parent and child aspect ratio.
if (containerWidth * contentHeight > containerHeight * contentWidth) {
// Max out the height. Calculate width while maintaining the aspect ratio.
fittedContentWidth = contentWidth * containerHeight / contentHeight;
fittedContentHeight = containerHeight;
} else {
// Max out the width. Calculate height while maintaining the aspect ratio.
fittedContentWidth = containerWidth;
fittedContentHeight = contentHeight * containerWidth / contentWidth;
}
return new Point(fittedContentWidth, fittedContentHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment