Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created December 6, 2024 10:03
Show Gist options
  • Save shaobin0604/80b6d646a2eede9e76a7d40c5c32533e to your computer and use it in GitHub Desktop.
Save shaobin0604/80b6d646a2eede9e76a7d40c5c32533e to your computer and use it in GitHub Desktop.
ImageView ScaleType.CENTER_CROP 实现逻辑
class Scratch {
private static int[] calculateCropPercent(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
float targetAspect = (float) dstHeight / (float) dstWidth;
int outWidth, outHeight;
if (srcHeight > srcWidth * targetAspect) {
// limited by narrow width; reduce height
outWidth = srcWidth;
outHeight = (int) (srcWidth * targetAspect);
} else {
// limited by short height; restrict width
outHeight = srcHeight;
outWidth = (int) (srcHeight / targetAspect);
}
int[] outOffset = new int[]{(srcWidth - outWidth) / 2, (srcHeight - outHeight) / 2};
float[] outOffsetPercent = new float[]{outOffset[0] / (float) srcWidth, outOffset[1] / (float) srcHeight};
System.out.println("src: " + srcWidth + "x" + srcHeight);
System.out.println("dst: " + dstWidth + "x" + dstHeight);
System.out.println("out: " + outWidth + "x" + outHeight);
System.out.println("outOffset: " + outOffset[0] + "x" + outOffset[1]);
System.out.println("outOffsetPercent: " + outOffsetPercent[0] + "x" + outOffsetPercent[1]);
return outOffset;
}
public static void main(String[] args) {
calculateCropPercent(720, 1280, 228, 180);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment