Java tutorial
//package com.java2s; //License from project: Open Source License import android.util.Pair; public class Main { private static Pair<Integer, Integer> clampDimensions(int inWidth, int inHeight, int maxWidth, int maxHeight) { if (inWidth > maxWidth || inHeight > maxHeight) { final float aspectWidth, aspectHeight; if (inWidth == 0 || inHeight == 0) { aspectWidth = maxWidth; aspectHeight = maxHeight; } else if (inWidth >= inHeight) { aspectWidth = maxWidth; aspectHeight = (aspectWidth / inWidth) * inHeight; } else { aspectHeight = maxHeight; aspectWidth = (aspectHeight / inHeight) * inWidth; } return new Pair<>(Math.round(aspectWidth), Math.round(aspectHeight)); } else { return new Pair<>(inWidth, inHeight); } } }